将一个物体沿直线路径移动到目标位置。

我又遇到了一个问题。所以,我正在使用 corona 制作游戏。我希望物体能够直线移动到触摸坐标。我知道我可以简单地使用 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

希望我的问题足够清楚明白。

点赞
用户1264811
用户1264811

你需要的东西比这个函数复杂。它只是简单地“接近”目的地。它没有遵循直线路径。为了完成你想要做的事情,你需要做以下几件事情:

  1. 找到你的位置。
  2. 找到目的地的位置。
  3. 计算从起点到终点的水平距离。
  4. 计算从起点到终点的垂直距离。
  5. 现在,如果你把这些加到你的起始对象上,你会立即到达目的地。我们如何让它慢慢移动呢?只需将垂直和水平距离除以一个“速度”变量。这是对象在一帧中移动的速度。
  6. 对于每一帧,通过添加刚刚找到的x和y分量来更新对象。
  7. 检查是否到达目的地。必要时重复步骤6。(或者:跟踪你已经行驶了多少水平和垂直距离并将其与原始结果进行比较。)

这就是全部!

2013-07-25 01:14:01
用户1605727
用户1605727

试试我的示例应用。你可以使用此应用或从中获取项目思路。

你也可以在空白项目中测试它,以了解它的工作原理。

_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)

    --这个条件将停止圆圈在触摸坐标上
    --您可以更改面积值,这将检测圆的x和y是否在圆的tx和ty之间
    --如果面积为0,则可能无法停止圆圈,面积=5是安全的,如果需要可以更改
    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) --将速度设置为(0,0),以完全停止圆圈
    end
end

--添加事件侦听器以监视圆圈的坐标
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 --计算到X和到Y坐标
        local sppedMultiplier = 1.5 --这会改变圆圈的速度,0值会使圆圈停止

        --设置圆圈的未来位置
        circle.tx = x
        circle.ty = y

        circle:setLinearVelocity(tx*delay,ty*delay) --这将在一条直线上将圆圈的速度设置为计算出的触摸坐标。
    end
end)
2013-07-25 01:26:09
用户8261574
用户8261574

这是移动圆形到触摸点的数学公式:

    theta = atan2(touchY - circle.y,touchX - circle.x)
    velx = cos(theta)
    vely = sin(theta)
    circle.x += velx
    circle.y += vely

随着圆形接近触摸点,速度将趋近于0。

2020-08-16 04:57:48