You made it so the centers of the circles 'collide'.
You'll need something like
if (TX + 25 + 60) >= Xpos then --25 and 60 being the radiuses of the circles
TX = TX - 35
end
Additionally.
In your code the following will execute only once:
if Xpos == TX then
Xpos = Xpos + 0.1
end
This is because Xpos
is 300
, TX
is 50
. On each iteration with right arrow held the TX
increases by 5
. This way TX
reaches 300
at some point. Now Xpos
becomes 300.1
and TX == Xpos
will never again be true, because TX
is moving in increments of 5
and as such will never have the value 300.1
. In my updated code it will not trigger at all because the centers of the circles will never intersect.
If you wan to check for the moment of collision, you should use the collision detection itself:
if (TX + 25 + 60) >= Xpos then --25 and 60 being the radiuses of the circles
TX = TX - 35
--add code here
end
Furthermore, your code is suboptimal and the speed of the circle will be affected by frames per second (some situations might require it, but in games, you don't want this) you should separate the movement and collision detection to 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
The final code will be something like this:
win = love.window.setMode(600, 600)
Xpos = 300
Xpos_radius = 25
TX = 50
TX_radius = 60
function love.update(dt)
if love.keyboard.isDown("right") then
TX = TX + 150 * dt
end
if (TX + Xpos_radius + TX_radius) >= Xpos then
TX = TX - 35
--Xpos = Xpos + 1 --if you want to slowly bump the white ball away
end
end
function love.draw()
love.graphics.setColor(1, 1, 1)
love.graphics.circle("fill", Xpos, 200, Xpos_radius)
love.graphics.setColor(1, 0, 0)
love.graphics.circle("fill", TX, 200, TX_radius)
end
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…