我正在使用this simple virtual joystick module,我正试图让我的播放器根据操纵杆的角度在360度方向旋转,但它无法正常工作。
以下是该模块中最相关的代码:
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
以下是我在设置操纵杆后尝试移动播放器的方法:
local angle = joyStick.getAngle()
player.rotation = angle
angle
和player.rotation
具有完全相同的值,但播放器的旋转方向与操纵杆的方向不同,因为操纵杆的默认0旋转朝向正确的方向(东方)并且它反向 - 顺时针方向旋转。
答案 0 :(得分:2)
试试player.rotation = -angle
。 player
和joystick
应朝同一方向旋转。
使用simpleJoystick模块,你得到(度)
NORTH - 90
WEST - 180
EAST - 0/360
SOUTH - 270
如果你想获得
NORTH - 0
WEST - 90
EAST - 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)
...