How can I choose a sheep’s random direction only once per movement period?

September 11, 2026 2 answers
Asked by Genealogist
I'm making sheep that move automatically, pause for a while, and then choose either LEFT or RIGHT at random. The problem is that sheep_mvmt() is called every frame, and it currently calls rand() every time. That means the direction is being selected repeatedly while the sheep is moving instead of once when it leaves the IDLE state. How should I structure the state and timer logic so the sheep keeps its chosen direction until the movement period ends?

Answers

soup ladle study
The random choice is happening inside sheep_mvmt(), which runs once per frame. Pick the direction when the sheep changes from IDLE to moving, store it in sheep1.state, and let the movement function only move according to that stored state. For example: if (sheep_counter >= 120 && sheep1.state == IDLE) { sheep1.state = static_cast((rand() % 2) + 1); } 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; } } This way rand() is called only when the sheep starts moving.

Genealogist: That makes sense. I was choosing a direction inside the movement function, so it kept changing every frame. I need to update the stored state when the movement cycle starts instead.

Reply to this answer
split1min
You can also base the transition on elapsed time rather than counting frames. Keep a movement timer, and when it expires, choose LEFT or RIGHT once and reset the timer. During the movement interval, never call rand(); just use the current state. This also works better if the frame rate changes. The important separation is: state selection belongs in the state-transition code, while sheep_mvmt() should only apply velocity based on the already-selected state.

_36th proposition: The same idea can be used for distance instead of time: choose a direction once, move until the sheep reaches its target distance, then switch to IDLE and choose another direction on the next transition.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions