2016-11-20 96 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