Search code examples
luarotationcoronasdkjoystick

360 virtual joystick rotation


I'm using this simple virtual joystick module, I'm trying to get my player to rotate in 360-degrees direction according to the joystick's angle, but it's not working right.

Here is the most relevant code from the module:

local radToDeg = 180/math.pi
local degToRad = math.pi/180

-- where should joystick motion be stopped?
local stopRadius = outerRadius - innerRadius

local directionId = 0
local angle = 0
local distance = 0

function joystick:touch(event)

        local phase = event.phase

        if( (phase=='began') or (phase=="moved") ) then
            if( phase == 'began' ) then
                stage:setFocus(event.target, event.id)
            end
            local parent = self.parent
            local posX, posY = parent:contentToLocal(event.x, event.y)
            angle = (math.atan2( posX, posY )*radToDeg)-90
            if( angle < 0 ) then
                angle = 360 + angle
            end

            -- could expand to include more directions (e.g. 45-deg)
            if( (angle>=45) and (angle<135) ) then
                directionId = 2
            elseif( (angle>=135) and (angle<225) ) then
                directionId = 3
            elseif( (angle>=225) and (angle<315) ) then
                directionId = 4
            else
                directionId = 1
            end

            distance = math.sqrt((posX*posX)+(posY*posY))

            if( distance >= stopRadius ) then
                distance = stopRadius
                local radAngle = angle*degToRad
                self.x = distance*math.cos(radAngle)
                self.y = -distance*math.sin(radAngle)
            else
                self.x = posX
                self.y = posY
            end

        else
            self.x = 0
            self.y = 0
            stage:setFocus(nil, event.id)

            directionId = 0
            angle = 0
            distance = 0
        end
        return true
    end

function joyGroup:getAngle()
    return angle
end

Here is how I try to move my player after setting up the joystick:

 local angle = joyStick.getAngle()  
 player.rotation = angle 

angle and player.rotation have the exact same values, but the player rotates in a different direction than the joystick because the joystick's default 0 rotation is towards the right direction (East) and it goes counter-clockwise.


Solution

  • Try player.rotation = -angle. The player and joystick should rotate in the same direction.

    With simpleJoystick module you get (in degree)

    NORTH - 90

    WEST - 180

    EAST - 0/360

    SOUTH - 270

    If you want get

    NORTH - 0

    WEST - 90

    EAST - 270

    SOUTH - 180

    modify code in simpleJoystick module like this

    ...
    angle = (math.atan2( posX, posY )*radToDeg)-180
    ...
    self.x = distance*math.cos(radAngle + 90*degToRad)
    self.y = -distance*math.sin(radAngle + 90*degToRad)
    ...