Game Development Reference
In-Depth Information
Moving the character with actions
Let's discover how we can add simple player movements to our game, for example,
jumping. One of the ways to handle this could be by creating a new action that will
move the character up by a certain amount of pixels and then move the character
down. Let's try this out.
Remove everything from the touchesBegan: method in ERGMyScene.m . It should
look like this:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// we are creating action to move the node that runs it by vector
// of x and y components with duration in seconds
SKAction *moveUp = [SKAction moveBy:CGVectorMake(0, 100)
duration:0.8];
// same as before, but it is opposite vector to go down, and it is
a bit
// faster, since gravity accelerates you
SKAction *moveDown = [SKAction moveBy:CGVectorMake(0, -100)
duration:0.6];
// sequence action allows you to compound few actions into one
SKAction *seq = [SKAction sequence:@[moveUp, moveDown]];
// childNodeWithName: method allows you to find any node in
hierarchy with
// certain name. This is useful if you don't want to store things
// as instance variables or properties
ERGPlayer *player = (ERGPlayer *)[self
childNodeWithName:playerName];
// after creating all actions we tell character to execute them
[player runAction:seq];
}
If you tap now, the character sprite will jump (that is, move up and then go down).
Notice that we didn't write anything regarding the player in the update loop and
it still works. The actions system is separate from the update loop. If we set some
player movement in the update: method, they would work simultaneously,
running the action for a duration and updating every frame. Also, notice that if you
jump a couple of times, these will all stack up and work awkwardly. We could fix
this by adding a variable that tells us whether the character is in the middle of a
jump, and further jump and other actions should be ignored.
 
Search WWH ::




Custom Search