love2D无法弄清楚如何使两个圆基本碰撞不会产生错误

问题描述

我正在尝试做到这一点,以使当我的红色圆圈碰到我的白色圆圈时,当我运行代码时,红色圆圈将向后移动一步,但我尝试的碰撞不起作用。它恰好穿过白色圆圈。 这是代码

win = love.window.setMode(600,600)
Xpos = 300
TX = 50

function love.draw()
    love.graphics.setColor(1,1,1)
    love.graphics.circle("fill",Xpos,200,25)
    love.graphics.setColor(1,0)
    love.graphics.circle("fill",TX,60)

    if Xpos == TX then 
        Xpos = Xpos + 0.1
    end

    if TX >= Xpos then
        TX = TX - 35
    end

    if love.keyboard.isDown("right") then
        TX = TX + 5
    end
end

解决方法

您成功做到了,使圆心“碰撞”。 您需要类似

的东西
if (TX + 25 + 60) >= Xpos then    --25 and 60 being the radiuses of the circles
    TX = TX - 35
end

此外。 在您的代码中,以下内容仅执行一次:

if Xpos == TX then 
   Xpos = Xpos + 0.1
end

这是因为Xpos300TX50。在每次带右箭头的迭代中,TX增加5。这样TX会在某个时刻到达300。现在Xpos变为300.1TX == Xpos将不再为真,因为TX5的增量移动,因此将永远不会具有值{{ 1}}。在我更新的代码中,它根本不会触发,因为圆心永远不会相交。

如果要检查碰撞时刻,您应该使用碰撞检测本身:

300.1

此外,您的代码不是最理想的,圆的速度将受到每秒帧数的影响(某些情况下可能需要它,但是在游戏中,您不希望如此),您应该分开if (TX + 25 + 60) >= Xpos then --25 and 60 being the radiuses of the circles TX = TX - 35 --add code here end

的运动和碰撞检测
love.update

最终代码将如下所示:

function love.update(dt)
    --first move the circle,--then check for collisions to avoid visible intersections
    if love.keyboard.isDown("right") then
        TX = TX + 150 * dt    --move the circle by 150 pixels every second
    end
    if (TX + 25 + 60) >= Xpos then
        TX = TX - 35
    end
end