在我的项目中,如果我拖动一个对象,会在对象上施加一个力并生成另一个对象 并按手指滑动的方向移动,并根据施加的力量,此代码正常工作。但我想根据手指滑动的角度旋转生成的第二个对象。我想知道如何获得手指滑动的角度并将第二个物体旋转到该角度,请提出任何建议。谢谢... 手指滑动代码如下:
local Objectswipe = display.newImage( "object1.png")
Objectswipe.x = 100
Objectswipe.y = 200
target = display.newImage( "target.png" )
target.x = Objectswipe.x; target.y = Objectswipe.y; target.alpha = 0
local function fingerswipe( event )
local t = event.target
local phase = event.phase
if "began" == phase then
display.getCurrentStage():setFocus( t )
t.isFocus = true
t:setLinearVelocity( 0, 0 )
t.angularVelocity = 0
target.x = t.x
target.y = t.y
startRotation = function()
target.rotation = target.rotation + 4
end
Runtime:addEventListener( "enterFrame", startRotation )
local showTarget = transition.to( target, { alpha=0.4, xScale=0.4, yScale=0.4, time=200 } )
myLine = nil
elseif t.isFocus then
if "moved" == phase then
if ( myLine ) then
myLine.parent:remove( myLine ) -- erase previous line, if any
end
myLine = display.newLine( t.x,t.y, event.x,event.y )
myLine:setColor( 255, 255, 255, 50 )
myLine.width = 8
elseif "ended" == phase or "cancelled" == phase then
display.getCurrentStage():setFocus( nil )
t.isFocus = false
local stopRotation = function()
Runtime:removeEventListener( "enterFrame", startRotation )
end
local hideTarget = transition.to( target, { alpha=0, xScale=1.0, yScale=1.0, time=200, onComplete=stopRotation } )
if ( myLine ) then
myLine.parent:remove( myLine )
end
t:applyForce( (t.x - event.x), (t.y - event.y), t.x, t.y )
end
end
return true
end
Objectswipe:addEventListener( "touch", fingerswipe )
答案 0 :(得分:2)
试试我创建的这个示例应用。我一直都在使用这个功能。
local physics = require("physics")
physics.start()
physics.setGravity(0,0)
physics.setDrawMode("debug")
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)+360)%360
local mult = 10^0
return math.floor(angleInDegrees * mult + 0.5) / mult
end
local c = display.newCircle(0,0,50)
c.x = display.contentWidth/2
c.y = display.contentHeight/2
physics.addBody(c,"dynamic",{radius = 50})
Runtime:addEventListener("touch",function(event)
if event.phase == "began" then
elseif event.phase == "moved" then
local angle = getAngle(c.x,c.y,event.x,event.y)
print(angle)
c.rotation = angle
elseif event.phase == "ended" then
end
end)
答案 1 :(得分:0)
你做的事情如下:
local point1 = {}
local point2 = {}
--save the coordinates for the ended phase
if event.phase == "ended" then
point1.x = event.xStart
point1.y = event.yStart
point2.x = event.x
point2.y = event.y
end
--arbitrary third point
point3 = {}
point3.x = point2.x
point3.y = point1.y
然后你会有三个点,并可以计算角度。你应该能够以一定的角度施加力。