Quick tip - how to get a consistent speed using transition.to

Here’s some things other readers here might find helpful. I’m a newbie with Corona and shouldn’t be posting tips :slight_smile: but this code has helped me a lot this week. This is just my method that has worked.

The problem: If you’re moving an actor on the stage between points, you’ll get inconsistent speeds over different distances. As transitions are time based, a character will speed over a short distance and take longer to move over a longer distance.

Here’s the code you’ll need to move an actor using transition.to over any distance with a consistent pace. In this example, actor_name has to move to a display_image target_image. Target image can be set when someone clicks.

  1. Add a speed setting:

[lua]-- number of pixels to move per second
actor_speed = 100;[/lua]

  1. Add this function to your code, which works out the distance between two points on the screen (this is not my function - thank you to IgnisDesign for posting it originally…):

[lua]local function distanceBetween( point1, point2 )

local xfactor = point2.x-point1.x ; local yfactor = point2.y-point1.y
local distanceBetween = math.sqrt((xfactor*xfactor) + (yfactor*yfactor))
return distanceBetween

end[/lua]

  1. Next we need to calculate the distance between the starting point and the end point of the movement of your actor:

[lua]local distance = distanceBetween(actor_name, target_image);[/lua]

  1. Work out the time that we’ll need to add later into the transition to.

[lua]local time_taken = distance / actor_speed * 1000;[/lua]

  1. Now make the transition like this:

[lua]-- move the actor
transition.to(actor_name, {x=target_x, y=target_y, time=time_taken});[/lua]

This movement is handy for games in Corona.

Thanks

Tom [import]uid: 55068 topic_id: 10652 reply_id: 310652[/import]

Hey there,

Thanks for sharing this, I am sure a lot of people will find it very handy!

Peach :slight_smile: [import]uid: 52491 topic_id: 10652 reply_id: 38690[/import]

I was looking for a way to do that! Thanks! [import]uid: 48658 topic_id: 10652 reply_id: 38723[/import]

xFactor & yFactor is really dX, dY, or distanceX, distanceY.

[import]uid: 4596 topic_id: 10652 reply_id: 38813[/import]