Need Help with Collisions

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
LateLama
Prole
Posts: 2
Joined: Fri Apr 21, 2017 12:11 am

Need Help with Collisions

Post by LateLama »

Hey everyone!
I'm a big noob (just started today), so pardon me if I say something stupid.
I was trying to make a collision happen between a rectangle and a moving circle. I know the way I set it up surely isn't the right one, but I can't understand why it won't work.
So, imagine the circle starting in the middle of the window and a rectangle at the same height, but left. I have a function updating the circle which makes it move left in the beginning. When the left side of the circle meets the right side of the rectangle, it should start moving to the right. This won't happen though: it just goes through it. Something even stranger happens when changing "b_left = a_right" with "b_left < a_right".
Sorry for my bad English, I hope I made it understandable enough.

Code: Select all

function Circle:update(dt)
  i = 1
  if Circle.checkCollision(r1,c) then
    i = i + 1
  end
  if (i%2 == 0) then
    self.x = self.x + self.speed * dt
  else
    self.x = self.x - self.speed * dt
  end
end

function Circle.checkCollision(a,b)
  a_left = a.x;

  b_left = b.x - b.radius;

  if b_left = a_right  then
    return true
  else
    return false
  end
end
User avatar
raidho36
Party member
Posts: 2063
Joined: Mon Jun 17, 2013 12:00 pm

Re: Need Help with Collisions

Post by raidho36 »

You cannot just check floating point numbers for equality - it's pretty much guaranteed to fail. That's because there's only so many digits available, and inevitably precision errors accumulate. What you'd normally do is check if the value falls within some very small range, to accomodate for computation errors, called epsilon.

On top of that, your object doesn't travel continuously, but in discrete and pretty large steps - you add speed × dt to its coordinate at once. Chances are if you simply try to check if the object is in very specific position, it will also pretty much always fail due to large step size, even if you use epsilon range check.

Finally, what you really want to do is check if object A crossed boundary of object B. Emphasis on "crossed". I.e. when leading edge of an object was on the left hand side of another object's leading edge and becomes positioned on the right hand side.
LateLama
Prole
Posts: 2
Joined: Fri Apr 21, 2017 12:11 am

Re: Need Help with Collisions

Post by LateLama »

Yeah, I just figured out what you said about floats when I printed the position on screen. Didn't really think about the fact that I'm not moving the circle continuosly.
Thank you for the help!
Post Reply

Who is online

Users browsing this forum: Google [Bot] and 159 guests