I am making a game. I would like to have a joystick that moves the character around the screen. Kinda like a video game controller. Any help would be greatly appreciated! Thanks!
Here is what I am currently using, guys. From looking at it, I don’t think that it generates an input:
-(id) init
{
if( (self=[super initWithColor:ccc4(255,255,255,255)] )) {
self.isTouchEnabled = YES;
SneakyJoystickSkinnedBase *leftJoy = [[[SneakyJoystickSkinnedBase alloc] init] autorelease];
leftJoy.position = ccp(72,72);
leftJoy.backgroundSprite = [CCSprite spriteWithFile:@"dpad.png"];
leftJoy.thumbSprite = [CCSprite spriteWithFile:@"joystick.png"];
leftJoy.joystick = [[SneakyJoystick alloc] initWithRect:CGRectMake(0,0,128,128)];
leftJoyStick = [leftJoy.joystick retain];
[self addChild:leftJoy];
[[CCDirector sharedDirector] setAnimationInterval:1.0f/60.0f];
}
return self;
}
You can get
directionandspeedfrom thevectorproduced by the joystick. Usually, joystick input generates normalized 2d position whose x and y values are between -1 and 1. For example, Up is (0, 1.0), Right is (0, 1.0), Left is (-1.0, 0) and Down is (0, -1.0). Once you have this input vector, you can get the two values.Set your character’s
look-atvector (it is a normalized vector representing character’s current direction) todirection. If you want to rotate the character smoothly, do interpolation from the currentlook-atvector todirectionin your update.Update your character’s
positionwith thespeednew_position = current_position + look-at * speed * time;
You can see there are two movements, rotating and forwarding. People usually set two different speed constants to control them. You can also do one at a time like rotating first and then forwarding. Good Luck! 🙂
[UPDATE]
Well, if you don’t want to rotate it, you can just do step 2 with “direction” instead of “look-at”. Also, you can produce “input vector” by subtracting the
center positionof the joystick fromthe actual movement(I assume this is a position from the joystick) and then, normalize it.