将物体围绕中心旋转

事情是这样的,我在我的游戏中有一门大炮,我想用手指来转动它。我希望炮口始终指向手指拖动的相反方向,即如果手指向左下拖动,则炮口应该指向右上。

我只是无法弄清楚如何使它正常工作。我已经成功地使用以下代码将其旋转:

local function rotateObj(event)
    local t = event.target
    local phase = event.phase

    if (phase == "began") then
        display.getCurrentStage():setFocus(t)
        t.isFocus = true

        -- 存储手指的初始位置
        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

            -- 旋转
            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

    -- 阻止触摸事件的进一步传播
    return true
end
cannon:addEventListener("touch", rotateObj)

虽然这确实允许我旋转我的大炮,但它不会保持炮口与我拖动的位置的关系。我甚至不知道该从哪里开始。

点赞
用户1605727
用户1605727

你可以试试我的代码。

我也创建了一个类似于你的游戏,但你是控制弓箭的。

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
        -- 如果你的图片原本朝向北方,则使用 +90 
        -- 如果你的图片原本朝向东方,则使用 +180
        -- 如果你的图片原本朝向南方,则使用 +270 
        -- 如果你的图片原本朝向西方,则使用 +360 或 +0

        -- 我的 wind_arrow.png 是朝向东方的,因此我使用 +180 
        -- 你可以使用这个公式
        arrow.rotation = (getAngle(arrow.x,arrow.y,event.x,event.y)+180)*-1
    end 
end
Runtime:addEventListener("touch",arrow)
2013-06-14 01:23:09
用户1212870
用户1212870

看一下你的第一个 if else if 语句:

if (phase == "began") then
    t.isFocus = true
elseif t.isFocus then
    XXX
end

phase == "began" 时,它将不起作用,因为 if else if 语句只会进入其中一条路径。在你的 if 语句中,你将 t.isFocus 设置为 true,但是它在 elseif 路径中不会立即被判断。

2013-06-14 01:25:43