Page 1 of 1

I need help with making a collision resolver

Posted: Mon Nov 23, 2020 3:16 pm
by breuning
Hey! I am new to LOVE and just started making a 2D platformer game.
I have already successfully written a function to determine whether two game objects are colliding:

Code: Select all

function collision(obj1,obj2)
return (obj1.pos - obj2.pos):magnitude() < ((obj1.size*0.5)+(obj2.size*0.5)):magnitude()
end

function Vector2:magnitude()
    return math.sqrt((self.x^2 + self.y^2))
end
with pos and size being Vector2

Now I'm having a hard time trying to figure out how to calculate the vector that I need to add to the player character in order to push him out of solid objects, so that I can build walls and platforms.
What I basically need is the vector describing the rectangle created by two overlapping rectangles. I've been sitting at this for an hour getting reminded how much I suck at linear algebra.

I'd be very grateful if someone could give me an equation or help me in any way :)

Re: I need help with making a collision resolver

Posted: Tue Nov 24, 2020 11:54 am
by pgimeno
breuning wrote: Mon Nov 23, 2020 3:16 pm What I basically need is the vector describing the rectangle created by two overlapping rectangles.
The intersection of two rectangles is a rectangle that can be calculated this way:

Code: Select all

local function intersection(r1, r2)
  local x1 = math.max(r1.x1, r2.x1)
  local y1 = math.max(r1.y1, r2.y1)
  local x2 = math.min(r1.x2, r2.x2)
  local y2 = math.min(r1.y2, r2.y2)
  if x1 >= x2 or y1 >= y2 then
    return false -- they don't intersect
  end
  return {x1 = x1, y1 = y1, x2 = x2, y2 = y2}
end

Re: I need help with making a collision resolver

Posted: Tue Nov 24, 2020 11:57 am
by breuning
pgimeno wrote: Tue Nov 24, 2020 11:54 am
The intersection of two rectangles is a rectangle that can be calculated this way:

Code: Select all

local function intersection(r1, r2)
  local x1 = math.max(r1.x1, r2.x1)
  local y1 = math.max(r1.y1, r2.y1)
  local x2 = math.min(r1.x2, r2.x2)
  local y2 = math.min(r1.y2, r2.y2)
  if x1 >= x2 or y1 >= y2 then
    return false -- they don't intersect
  end
  return {x1 = x1, y1 = y1, x2 = x2, y2 = y2}
end
Thanks, I'll try that :D