Silverback Logo
Follow stssupport on Twitter
Silverback Technology Solutions

Constant speed using Cocos2D CCMoveTo action.

12/04/2011 Share/Bookmark

I've been tinkering with my latest game concept and I needed to move my enemy sprites to a given location.  To do this I thought the simplest way to achieve this was by using the the CCMoveTo action class.

Here's the code I used to start with;

[enemySprite runAction:[CCMoveTo actionWithDuration:2.0f  position:CGPointMake(size.width/2,size.height/2)]];

Now this works perfectly well, apart from the fact that the sprites further away move towards the target location at a greater speed, this is because each sprite performs the action over the same time frame (2 seconds) no matter where they appeared.


So I needed to devise a better way of doing this action that would move the enemy sprites at a different speed, depending on if they are nearer or further away from the target.   This required some maths and thanks to some googling I discovered the main formula required to calculate the distance between the two points, this is the formula written down;
sqrt((x2-x1)^2 + (y2-y1^2))
This would give me the distance between two points, but I need to calculate the time needed to travel the distance, I therefore came up with the following code block to give me what I needed;

-(float)getEnemyTimeToPoint:(CGPoint)targetPoint fromPoint:(CGPoint)sourcePoint speed:(int)travelSpeed {
    return sqrt( pow((targetPoint.x-sourcePoint.x),2) + pow((targetPoint.y-sourcePoint.y),2) ) / travelSpeed;
}


This piece of code takes a target point and a source point, calculates the distance between them and then divides the result by a travel speed (i.e. the number of pixels a sprite will travel in 1 second).  The result returned is the number of seconds the enemy will travel over the distance of the two points.

We can therefore now change our original code to move the enemy sprites as follows;

[enemySprite runAction:[CCMoveTo actionWithDuration:[self getEnemyTimeToPoint:CGPointMake(size.width/2, size.height/2) fromPoint:[enemySprite position] speed:60] position:CGPointMake(size.width/2, size.height/2)]];

To change the speed of the sprites we simply subtract from the supplied speed value (i.e. speed:40) so they move faster, or add to it (i.e. speed:80) to make them move slower.

No comments:

Post a Comment

About Me

My photo
Software developer working on iPhone Apps and Games in spare time. Full time job is working with a corporate IT company supporting and developing various software installations.

© Silverback Technology Solutions