試試我的示例應用程序。你可以使用這個或爲你的項目得到一個想法。
你也可以在一個空白的項目中測試它,看看它是如何工作的。
_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)