For the use of the community as a whole, I’m posting 2 math “helper” functions which I wrote and use for my own development. There is nothing really special about these; they use common geometry/trig formulas. Many of you have probably written your own already. If not, and if you need these for your game, please go ahead and use them. 
Distance Between (two points/objects)
This is useful for alot of purposes. One of the most obvious is using this to calculate “constant” movement transitions. Since Corona utilizes time-based transitions, an object will move from point A to point B in a certain time, but the distance is not factored in. So, you’ll get faster object movement when the points are farther apart. Using the DistanceBetween function, you can check the distance and use it as the divisor of a time amount, ensuring consistent movement speeds.
Here’s the function. Pass two objects/events/whatever that contain an X and Y position. The function returns the distance between them. Notice that I used “x*x” and “y*y” for the squaring math, versus math.pow() or x^2 because Ansca says “x*x” is faster performance-wise.
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
Angle Between (two points/objects)
This one is useful for determining the rotation angle between two objects. For example, if two objects collide, you can call this function to determine the angle between them at the exact moment of collision. Another use might be to pass a click/touch position as one of the arguments, and set the other argument’s rotation to that angle… i.e. if you have a tank, you can click somewhere on the screen and the tank will rotate to face that touch location (via a transition) or just snap to that rotation instantly (object.rotation = ...).
srcObj can be your player or whatever; dstObj can be a touch location, another object on the screen (i.e. some enemy), or another object involved in a collision with the srcObj.
local function angleBetween ( srcObj, dstObj )
local xDist = dstObj.x-srcObj.x ; local yDist = dstObj.y-srcObj.y
local angleBetween = math.deg( math.atan( yDist/xDist ) )
if ( srcObj.x \< dstObj.x ) then angleBetween = angleBetween+90 else angleBetween = angleBetween-90 end
return angleBetween
end
If you have any suggestions on how to improve them or make them more efficient, please let me know. These functions can obviously be bundled into an external module if you prefer, or just included at the top of your main.lua file and called like normal functions.
Brent Sorrentino
Ignis Design LLC [import]uid: 9747 topic_id: 3709 reply_id: 303709[/import]