tetris11
tetris11

Reputation: 817

How do I converge to and fro, between two numbers?

I'm trying to animate a man running:

Frames 1 to 5 = man leaning into run. Frames 6 to 15 = man running a single step

frame = 1           
frame +=1         //frames progress forwards at rate of 1 frame 

function run(){
   if(frame>15){     //at frame 15: man has completed leaning into run and completed one 'running' cycle
       frame -=2      //frames now start to go backwards at rate of (1-2=)-1 frame
       if(frame<6){   //until they reach frame 6 (beginning of running animation)
           frame +=2  //frames start to progress forwards again at rate of (2-2+1=)+1 frame again

My method is really bad and seems to be only capable of going forwards then backwards ONCE between 15 and 6.

Does anyone know how I can bounce between these two numbers indefinitely?

Upvotes: 1

Views: 156

Answers (2)

tetris11
tetris11

Reputation: 817

Ok, so using LesterDove's + schnaader's useful tips I've managed:

int step=1

function run(){
    frame += step
    if(frame>15){ step = -1}
    if(frame<6){ step = 1}
}

and it works great guys. Thanks again!

Upvotes: 2

LesterDove
LesterDove

Reputation: 3044

After reaching frame = 15 and beginning your trip downward, you hit a condition (14) where neither of your IF statements is true. So your frame neither increments nor decrements. Stuck.

A possible better solution would be to maintain a variable called myDirection which toggles periodically between 1 and -1. That is, set myDirection = -1 when you hit 15, and set myDirection = 1 when you hit 6. Then, your iterative statement could always say frame = frame + myDirection and it would always be doing something -- you'd never be stuck doing nothing.

Upvotes: 6

Related Questions