360度虚拟摇杆旋转

我正在使用这个简单的虚拟摇杆模块,我正在尝试根据摇杆的角度使我的玩家在360度方向上旋转,但它没有正常工作。

这是模块中最相关的代码:

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

-- 摇杆运动何时应该停止?
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

            -- 可以扩展以包括更多方向(例如45度)
            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

这是我在设置摇杆后尝试移动我的玩家的方法:

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

angleplayer.rotation具有完全相同的值,但是玩家旋转的方向与摇杆不同,因为摇杆的默认0度旋转方向是向右(东)的,而且它是逆时针旋转的。

点赞
用户7026995
用户7026995

尝试使用 player.rotation = -angleplayerjoystick 应该向同一个方向旋转。

使用 simpleJoystick 模块时,你会得到以下角度值:

北 - 90

西 - 180

东 - 0/360

南 - 270

如果你想得到以下角度值:

北 - 0

西 - 90

东 - 270

南 - 180

修改 simpleJoystick 模块中的代码,如下所示:

...
angle = (math.atan2( posX, posY )*radToDeg)-180
...
self.x = distance*math.cos(radAngle + 90*degToRad)
self.y = -distance*math.sin(radAngle + 90*degToRad)
...
2016-11-21 09:31:41