2016-11-20 71 views
1

我正在使用this simple virtual joystick module,我试图让我的播放器根据操纵杆的角度在360度方向上旋转,但它不能正常工作。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 

angleplayer.rotation有相同的值,但是玩家的旋转方向与操纵杆不同,因为操纵杆的默认0度旋转是朝向正确的方向(东),逆时针旋转。

回答

2

尝试player.rotation = -angleplayerjoystick应该朝相同的方向旋转。

随着simpleJoystick模块你(在程度)

NORTH - 90

WEST - 180

EAST - 0/360

SOUTH - 270

如果你想获得

NORTH - 0

WEST - 90

EAST - 270

SOUTH - 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) 
... 
+0

“-angle + 90” 的伎俩,但现在问题在于玩家的默认旋转角度始终为90°(正确的方向),因为我在“enterFrame”中使用了此旋钮。有没有什么办法可以使操纵杆本身朝向上方向(北)转动0度,使其与正在旋转的物体变得相同? – Abdou023

+0

我不确定你想要什么,但我编辑了我的答案来解决你最后的问题。 – ldurniat

+0

非常感谢。那样做了。 – Abdou023