2013-07-24 46 views
0

我再次遇到問題。所以,我正在製作一款日冕遊戲。我想讓對象沿直線移動到觸摸座標。我知道我可以簡單地使用transition.to()函數,但物理引擎在轉換期間無法正常工作。我寫了下面的代碼,但是當然,這個圓圈並沒有直線移動。將對象移動到直線路徑中的目標位置

function controls(event) 
    if event.phase == "began" or event.phase == "moved" then 
     follow = true 
     touchX = event.x; touchY = event.y 
    end 

    if event.phase == "ended" then 
     follow = false 
    end 
end 

function playerMotion() 
    if follow == true then 
     if circle.y < touchY then 
      circle.y = circle.y + 1 
     elseif circle.y > touchY then 
      circle.y = circle.y - 1 
     end 

     if circle.x < touchX then 
      circle.x = circle.x + 1 
     elseif circle.x > touchX then 
      circle.x = circle.x - 1 
     end 
    end 
end 

希望我的問題很清楚。

回答

0

你將需要比這個功能更復雜的東西。它所做的只是「接近」目的地。它不遵循直線路徑。

來完成你想做什麼,你需要做的幾件事情:

  1. 找到你的位置。
  2. 找到目的地的位置。
  3. 計算從開始位置到結束位置的水平距離。
  4. 相同,除了垂直。
  5. 現在,如果您要將此添加到您的起始對象,您將立即在目的地。我們如何才能使其緩慢移動?用「速度」變量簡單地劃分垂直和水平距離。這是對象在一幀中移動的速率。
  6. 對於每一幀,通過添加剛剛找到的x和y組件來更新對象。
  7. 檢查您是否已到達目的地。必要時重複步驟6。 (OR:記錄你行進的水平和垂直距離,並與原始結果進行比較。)

你有它!

0

試試我的示例應用程序。你可以使用這個或爲你的項目得到一個想法。

你也可以在一個空白的項目中測試它,看看它是如何工作的。

_W = display.contentWidth 
_H = display.contentHeight 

local physics = require("physics") 

physics.start() 
physics.setGravity(0,0) 

local circle = display.newCircle(0,0,20) 
circle.name = "circle" 
circle.x = _W/2 
circle.y = _H/2 
circle.tx = 0 
circle.ty = 0 
physics.addBody(circle) 
circle.linearDamping = 0 
circle.enterFrame = function(self,event) 
    print(self.x,self.tx) 

    --This condition will stop the circle on touch coordinates 
    --You can change the area value, this will detect if the circles's x and y is between the circles's tx and ty 
    --If area is 0, it may not stop the circle, area = 5 is safe, change if you want to 
    local area = 5 
    if self.x <= self.tx + area and self.x >= self.tx - area and 
     self.y <= self.ty + area and self.y >= self.ty - area then 
     circle:setLinearVelocity(0,0) --set velocity to (0,0) to fully stop the circle 
    end 
end 

--Add event listener for the monitoring the coordinates of the circle 
Runtime:addEventListener("enterFrame",circle) 


Runtime:addEventListener("touch",function(event) 
    if event.phase == "began" or event.phase == "moved" then 
     local x, y = event.x, event.y 
     local tx, ty = x-circle.x, y-circle.y --compute for the toX and toY coordinates 
     local sppedMultiplier = 1.5 --this will change the speed of the circle, 0 value will stop the circle 

     --sets the future destination of the circle 
     circle.tx = x 
     circle.ty = y 

     circle:setLinearVelocity(tx*delay,ty*delay) --this will set the velocity of the circle towards the computed touch coordinates on a straight path. 
    end 
end)