Advertisement

8 directional Movement

Started by June 13, 2001 11:37 PM
1 comment, last by nino 23 years, 8 months ago
hi i need help with putting 8 directional movement into my tile based game I want it so that when the character is walking in one direction like East and i push the arrow key to make him walk West i want the sprite to spin through all directions from East to West instead of just suddenly facing West by default i have it so the character spins clockwise so if he''s facing South and i push the button to move North the sprite will go from Facing South to South-West, then West, then North-West then finally facing North. kungfudude: my problem is this: if the sprite is facing South and i want him to start walking South-East then i would push the down and right key to move diagonally South-East but the sprite then goes from facing South to facing South-West then West etc spinning clockwise until he is facing South-East instead of simply going from facing South to facing South-East i know this is hard to understand but i have to figure this out is there some sort of algorithm to figure out the shortest distance between each direction?? Thanks NiNo
Sure, that''s no problem. You give every direction a number between 0 and 7, increasing clockwise. It doesn''t matter where you start.

So what you do is subtract the target direction from the current direction, add 8 and get the remainder of the integer division:

delta = (current - target + 8) % 8

Now, there are 4 cases:

0: don''t have to turn
1...3: turn counterclockwise
4: turn 180° (direction arbitary)
5...7: turn clockwise

Hope that helped

- JQ
Infiltration: Losing Ground
"Simpson, eh?" -Mr. Burns
"Excellent!" -the above
~phil
Advertisement
class Dude{private:    direction_t current_direction;//direction_t is likely an intpublic:    bool TurnToward(direction_t desired_direction);    void Turn(direction_t change);    void SetCurrentDirection(direction_t new_direction);    direction_t GetCurrentDirection();};bool Dude::TurnToward(direction_t desired_direction){    direction_t turnby=desired_direction-GetCurrentDirection();    if(!turnby) return(false);//no need to turn, so return false    turnby-=(direction_t_max>>1);//direction_t_max is a constant somewhere in code. in an 8 direction system, direction_t_max will be 8.    if(!turnby)    {        Turn((rand()&1)<<2-1);//turn random direction: 1 or -1    }    else    {        Turn((turnby>0) ? (1) : (-1));    }    return(true);//a turn was made, so return true}void Dude::Turn(direction_t change){    current_direction+=change;    current_direction%=DIR_COUNT;    if(current_direction<0) current_direction+=direction_t_max;}void Dude::SetCurrentDirection(direction_t new_direction){    current_direction=0;    Turn(new_direction);}direction_t Dude::GetCurrentDirection(){     return(current_direction);}  

Get off my lawn!

This topic is closed to new replies.

Advertisement