有人能否请展示一下代码,让这两个物体发生碰撞?

以下是我的代码,我需要让这两个球碰撞。这两个球分别是 ball.png 和 soccer.png。我还将箭头键 / WASD 用于移动这两个球。如果球碰到屏幕边缘时也能发生碰撞的话那就太好了。

function love.load()
ball = love.graphics.newImage('ball.png')
speed = 300
x, y = 0,0
soccer = love.graphics.newImage('soccer.png')
speed2 = 300
x1, y1 = 20,20
end

function love.update(dt)
if love.keyboard.isDown("right") then
    x = x + (speed*dt)
end
if love.keyboard.isDown("left") then
    x = x - (speed*dt)
end
if love.keyboard.isDown("up") then
    y = y - (speed*dt)
end
if love.keyboard.isDown("down") then
    y = y + (speed*dt)
end
if love.keyboard.isDown("d") then
    x1 = x1 + (speed2*dt)
end
if love.keyboard.isDown("a") then
    x1 = x1 - (speed2*dt)
end
if love.keyboard.isDown("w") then
    y1 = y1 - (speed2*dt)
end
if love.keyboard.isDown("s") then
    y1 = y1 + (speed2*dt)
end
end

function love.draw()
love.graphics.draw(ball, x,y,0,0.5,0.5)
love.graphics.draw(soccer, x1,y1,0,0.25,0.25)
love.graphics.setBackgroundColor(0,255,0)
end
点赞
用户2765603
用户2765603

2D圆圈之间的碰撞检测非常简单:

只需计算中心点的平方距离(因为使用平方,所以不需要平方根,公式为 Δx²+Δy²)。 如果这个距离小于两个半径之和的平方((r1+r2)²),则发生碰撞。

接下来,你可能想要计算撞击速度的交换甚至考虑旋转(当我最后写一个使球体碰撞的游戏时,我没有考虑旋转)。

2015-06-03 00:10:58