事情就是这样,我在游戏中有一门大炮,我想用手指转动。我希望尖端总是指向手指拖动到的相反方向,即如果手指被拖到左下方,尖端应该指向右上角。
我无法弄清楚如何让它发挥作用。我已设法使用以下代码进行旋转:
local function rotateObj(event)
local t = event.target
local phase = event.phase
if (phase == "began") then
display.getCurrentStage():setFocus( t )
t.isFocus = true
-- Store initial position of finger
t.x1 = event.x
t.y1 = event.y
elseif t.isFocus then
if (phase == "moved") then
t.x2 = event.x
t.y2 = event.y
angle1 = 180/math.pi * math.atan2(t.y1 - t.y , t.x1 - t.x)
angle2 = 180/math.pi * math.atan2(t.y2 - t.y , t.x2 - t.x)
print("angle1 = "..angle1)
rotationAmt = angle1 - angle2
--rotate it
t.rotation = t.rotation - rotationAmt
print ("t.rotation = "..t.rotation)
t.x1 = t.x2
t.y1 = t.y2
elseif (phase == "ended") then
display.getCurrentStage():setFocus( nil )
t.isFocus = false
end
end
-- Stop further propagation of touch event
return true
end
cannon:addEventListener("touch", rotateObj)
虽然这确实允许我旋转我的大炮,但它并没有将尖端关系保持在我拖动的位置。我不知道从哪里开始。
答案 0 :(得分:1)
您可以尝试我的代码。
我也创造了一个像你这样的游戏,但是你控制着弓箭。
function getAngle(x1,y1,x2,y2)
local PI = 3.14159265358
local deltaY = y2 - y1
local deltaX = x2 - x1
local angleInDegrees = (math.atan2( deltaY, deltaX) * 180 / PI)*-1
local mult = 10^0
return math.floor(angleInDegrees * mult + 0.5) / mult
end
local arrow = display.newImage("wind_arrow.png")
arrow.x = display.contentWidth/2
arrow.y = display.contentHeight/2
arrow.touch = function(self, event)
print(event.phase)
if event.phase == "moved" then
--If your image is originally pointing to the north use +90
--If your image is originally pointing to the east use +180
--If your image is originally pointing to the south use +270
--If your image is originally pointing to the west use +360 or +0
--My wind_arrow.png is point to the east so I use +180
--You can use this formula
arrow.rotation = (getAngle(arrow.x,arrow.y,event.x,event.y)+180)*-1
end
end
Runtime:addEventListener("touch",arrow)
答案 1 :(得分:0)
看看你的第一个if elseif句子。
if (phase == "began") then
t.isFocus = true
elseif t.isFocus then
XXX
end
当阶段==“开始”时,它将无效,因为如果elseif句子将进入一条路径。
在你的if中,你将t.isFocus设置为true,但不会在elseif路径中立即判断它。