How can I choose a random sheep direction only once per movement period?
Asked by
Fandango
I'm making sheep that wander automatically: they should remain idle for a while, then randomly choose either LEFT or RIGHT and move in that direction for a set amount of time before becoming idle again. My current code calls sheep_mvmt every frame, and that function calls rand() each time, so the direction is regenerated on every frame instead of being selected once and preserved. How should I structure the state and timing logic so the random direction is chosen only when the sheep leaves IDLE?
Answers
Choose the direction when the sheep changes from IDLE to moving, then store that value in sheep1.state. The movement function should only move according to the already-selected state and should not call rand(). For example: `if (sheep_counter >= 120 && sheep1.state == IDLE) { sheep1.state = (rand() % 2) ? LEFT : RIGHT; sheep_counter = 0; } else if (sheep1.state != IDLE) { if (sheep1.state == RIGHT) sheep1.position.x += sheep1.velocity * dt; else if (sheep1.state == LEFT) sheep1.position.x -= sheep1.velocity * dt; if (sheep_counter >= 240) { sheep1.state = IDLE; sheep_counter = 0; } }`. The important part is that `rand()` runs during the IDLE-to-moving transition, not once per frame.
Reply to this answer
Right now `sheep_mvmt()` is called every frame, so `STATE pick = ...` keeps replacing the direction roughly 60 times per second. Random selection and movement are separate actions: select a state once, save it in the sheep, and have the update code use that saved state until the movement interval ends. A pointer is not needed for this; assigning directly to `sheep1.state` is enough.
Reply to this answer
Your enum values are typically `IDLE = 0`, `LEFT = 1`, and `RIGHT = 2`, so `(rand() % 2) + 1` does produce LEFT or RIGHT. However, a clearer and safer expression is `sheep1.state = (rand() % 2 == 0) ? LEFT : RIGHT;`. Also seed the random generator once during setup, as you already do; do not reseed it inside the game loop.
Reply to this answer
Add your answer
Answers are reviewed before publication.
simmer.12min: You can also base the timing on elapsed seconds instead of counting frames. Increment a timer with `dt`, choose a direction when the timer reaches the idle duration, and return to IDLE when it reaches the movement duration. That works consistently even if the frame rate changes.