# Cocos2D: Change animation based on joystick direction

I'm trying to get my figure to look in the right directions, based on the input of the joystick. So if I tilt left it looks left and the left animation is used, if I used right, it looks right and right animation is used, if up, then up, down, down and so on. I just get animation for front and back. Also if I press up I see the back of the figure correctly, but it won't go back into the original state when I don't press up anymore.

-(void)applyJoystick:(SneakyJoystick *)aJoystick forTimeDelta:(float)
deltaTime {
CGPoint scaledVelocity = ccpMult(aJoystick.velocity, 128.0f);
CGPoint oldPosition = [self position];
CGPoint newPosition =
ccp(oldPosition.x + scaledVelocity.x * deltaTime,
oldPosition.y + scaledVelocity.y * deltaTime);
[self setPosition:newPosition];
id action = nil;
int extra = 50;
if ((int) aJoystick.degrees > 180 - extra && aJoystick.degrees < 180 + extra) {
action = [CCAnimate actionWithAnimation:walkingAnimLeft restoreOriginalFrame:NO];

} else if ((int) aJoystick.degrees > 360 - extra && aJoystick.degrees < 360 + extra) {
action = [CCAnimate actionWithAnimation:walkingAnimRight restoreOriginalFrame:NO];
}

else if ((int) aJoystick.degrees > 90 - extra && aJoystick.degrees < 90 + extra) {
action = [CCAnimate actionWithAnimation:walkingAnimBack restoreOriginalFrame:NO];

}
else if ((int) aJoystick.degrees > 270 - extra && aJoystick.degrees < 270 + extra) {
action = [CCAnimate actionWithAnimation:walkingAnimFront restoreOriginalFrame:NO];
}

if (action != nil) {
[self runAction:action];
}
}
}

• Cue Samuel Jackson: Indents, motherflipper, do you use them!? – doppelgreener Jun 14 '12 at 13:41
• Could you explain that further? :) – Blade Jun 14 '12 at 17:14
• And now I get it: Yes I tried with flipX, which didn't work as intended. It flips the y sprite/animation, but not the x sprite. It doesn't even display that one. – Blade Jun 14 '12 at 19:46

My approach was more or less the right one. But the direction cue had to go somewhere completely different, and also had to be changed a little. It is now in

-(void)updateStateWithDeltaTime:(ccTime)deltaTime
andListOfGameObjects:(CCArray*)listOfGameObjects {
if (joystick.degrees > 60 && joystick.degrees < 120) {
if (self.characterState != kStateWalkingBack)
[self changeState:kStateWalkingBack];

} else if (joystick.degrees > 211 && joystick.degrees < 300) {
if (self.characterState != kStateWalkingFront)
[self changeState:kStateWalkingFront];

} else if (joystick.degrees > 301 && joystick.degrees < 360){
if (self.characterState != kStateWalkingRight)
[self changeState:kStateWalkingRight];

} else if (joystick.degrees > 121 && joystick.degrees < 210) {
if (self.characterState != kStateWalkingLeft)
[self changeState:kStateWalkingLeft];
}
[self applyJoystick:joystick
forTimeDelta:deltaTime];
}
}