Thread: Help with reacting to collision in my 2D sidescroller

1. Help with reacting to collision in my 2D sidescroller

To detect collision I'm using a rectangle for each entity in the game, but Im having trouble reacting to it in an appropiate way. What I was trying to do was find the smallest distance for the player to get out of the wall and then move it out, but I get disastrous results, here is the code:

Code:
```void Samus::collided(Entity *him)
{
int x1_x1 = m_rect.x1 - him->getRect().x1; // distance from my x1 to his x1
int x1_x2 = m_rect.x1 - him->getRect().x2; // distance from my x1 to his x2
int y1_y1 = m_rect.y1 - him->getRect().y1; // distance from my y1 to his y1
int y1_y2 = m_rect.y1 - him->getRect().y2; // distance from my y1 to his y2

if (x1_x1 < 0) x1_x1 *= -1;
if (x1_x2 < 0) x1_x2 *= -1;
if (y1_y1 < 0) y1_y1 *= -1;
if (y1_y2 < 0) y1_y2 *= -1;

switch (him->getInst())
{
case inst_floor:
if (y1_y1 < y1_y2 && y1_y1 < x1_x1 && y1_y1 < x1_x2)
{
m_y = him->getRect().y1 - height;
return;
}
if (y1_y2 < y1_y1 && y1_y2 < x1_x1 && y1_y2 < x1_x2)
{
m_y = him->getRect().y2;
return;
}
if (x1_x1 < x1_x2 && x1_x1 < y1_y1 && x1_x1 < y1_y2)
{
m_x = him->getRect().x1 - width;
return;
}
if (x1_x2 < x1_x1 && x1_x2 < y1_y1 && x1_x2 < y1_y2)
{
m_x = him->getRect().x2;
return;
}
break;
case inst_entity:
break;
case inst_samus:
break;
}
}```
What's a good way to react to collision in a game like this?
Here is the entire project if anyone is interested (Uses SDL)
http://files.upl.silentwhisper.net/u...descroller.zip
Sprites by Rogultgot.

object moves X-amount in a direction
check for collision
if collision, move object X-amount in opposite direction of previous move
draw

3. That works fine for x, but what do I do about y? the movement vector can be in any direction.

4. Ok here is what I'm trying to do now:
Code:
```void Entity::move(int milis, std::vector<Entity*> entities)
{
int x = m_x, y = m_y;

m_x += (milis*m_dx)/10;
for (int i = 0; i < entities.size(); i++)
{
if (entities[i] != this)
{
if (collides(entities[i]))
{
m_x = x;
}
}
}

m_y += (milis*m_dy)/10;
for (int i = 0; i < entities.size(); i++)
{
if (entities[i] != this)
{
if (collides(entities[i]))
{
m_y = y;
}
}
}
}```
Now what I'm trying to do here is, if you move in x and collide with something (other than yourself) move back to where you were in x, back to where you still hadn't collided. Then do the same thing with y.

But the character moves into stuff and gets trapped inside... why oh why would that happen if I'm moving it to where it still hadn't collided?

5. does that method give you problems with only diagonal movement, or all movement?

6. Damn I can't beleive I was being so stupid, the problem was that the rect of each figure was "out of date" when I checked for collision.

Thanks for trying to help anyway, and sorry for wasting your time.

7. no apologie needed

good luck!