Friday, June 14, 2013

Moving an Object at a Constant Rate Corona SDK

This is a pretty annoying issue with the transition.to method that Corona SDK has provided. The issue, is that with transition.to you set a speed.  A normal call to it might look like this.

transition.to (hero, {time = 500, x = event.x, y = event.y})

Now no matter where you tap, it will take a half second to get to the given point. If you click across the screen, it will speed across. Or if you click 5 pixels over, it will crawl toward that point.

So what if you want our hero to move at the same speed no matter where it's going?
The answer is an equation for the distance between two points.
    the distance formula


So that's it.You calculate the distance between the position of your hero, and the position you want to move it to, and that is it's speed. Note, that I multiply our result by 2 in order to slow down the hero movement. Feel free to change the 2 to whatever you need. I can imagine a game with enemies of varying speed and this could come handy.

Example:

Original point = 0, 0
New point = 100,100
math.sqrt((0-100)^2+(0-100)^2) = 141
Therefore, the hero will move 141 pixels in 141 ms.

Not too difficult, but for someone who hates math, this is a pain.

No comments:

Post a Comment