-2

I am trying to make it so that when my red circle touches my white circle the red circle will move back a step when i run the code the collision I tried does not work. It just goes right through the white circle. Here is the code

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, 0)
    love.graphics.circle("fill", TX, 200, 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
mDeram
  • 69
  • 1
  • 9

1 Answers1

1

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
IsawU
  • 430
  • 3
  • 12