Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]

How To Rotate Player Towards Joystick?
Started by marcelopotty0 Aug 12 2018 04:44 PM

1 reply to this topic
[TOPIC: post.html]


[GLOBAL: userInfoPane.html]
  • Observer

  • 2 posts
  • Corona SDK



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)

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)


joy:addEventListener("touch", mover)

how can I make the rotation of an object change depending on the distance to the joytstick

[TOPIC: post.html]

Michael Flad

[GLOBAL: userInfoPane.html]
Michael Flad
  • Contributor

  • 139 posts
  • Corona SDK

You need trig functions (atan2) to get the angle from your delta x/y values.


    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
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.