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

0
0
Asked By MellowOrbit7 On

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?

2 Answers

Answered By QuietMaple8 On

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.

BlueCactus31 -

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.

Answered By CopperNoodle42 On

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.

MellowOrbit7 -

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.