how can I make the rotation of an object change depending on the distance to the joytstick?
local personaje = display.newImage("survivor.png", ax, ay) personaje:scale(0.2,0.2) physics.addBody(personaje) local joy = display.newCircle(ax +100, ay + 200, 50) joy:setFillColor(0,0.2,0.8, 0.5) local function mover(event) if event.phase == "began" then personaje:setLinearVelocity( (event.x - joy.x), (event.y - joy.y)) elseif event.phase == "moved" then personaje:setLinearVelocity( (event.x - joy.x), (event.y - joy.y) ) personaje.rotation = (event.target.x - event.x) \*5 -- I tried this out but it doesn't work print((event.target.x - event.x)\*5) elseif ( event.phase == "ended" or event.phase == "cancelled" ) then personaje:setLinearVelocity(0, 0) end end joy:addEventListener("touch", mover)
how can I make the rotation of an object change depending on the distance to the joytstick
You need trig functions (atan2) to get the angle from your delta x/y values.
[lua]
local RAD2DEG = 180 / math.pi
local dx = joy.x - personaje.x
local dy = joy.y - personaje.y
local rad = -math.atan2( -dy, dx )
local deg = (rad * RAD2DEG) + 90
personaje.rotation = deg
[/lua]
I did it in single steps so it’s easy to follow.
First calculated the dx/dy value, then called atan2 but with -dy because the Corona coordinate system has y increasing downwards on the screen but the actual math for atan2 is for y going upwards.
next I used the negative of the result of atan2 because Coronas objects rotate clockwise but the results of atan2 are counterclockwise.
Then I scaled the rad into degrees as atan2 returns radians but the objects rotation is in degrees and last but not least added 90 degrees as 0 degrees in Corona means, upwards but in atan2 it’s to the right.
You need trig functions (atan2) to get the angle from your delta x/y values.
[lua]
local RAD2DEG = 180 / math.pi
local dx = joy.x - personaje.x
local dy = joy.y - personaje.y
local rad = -math.atan2( -dy, dx )
local deg = (rad * RAD2DEG) + 90
personaje.rotation = deg
[/lua]
I did it in single steps so it’s easy to follow.
First calculated the dx/dy value, then called atan2 but with -dy because the Corona coordinate system has y increasing downwards on the screen but the actual math for atan2 is for y going upwards.
next I used the negative of the result of atan2 because Coronas objects rotate clockwise but the results of atan2 are counterclockwise.
Then I scaled the rad into degrees as atan2 returns radians but the objects rotation is in degrees and last but not least added 90 degrees as 0 degrees in Corona means, upwards but in atan2 it’s to the right.