# 2D stop on collision

So, this is the code I have right now:

if (keysPressed.Count() > 0)
{
switch (keysPressed[0])
{
case Keys.W:
{
characterStats.Velocity.Y += velocityCahge*(-1);
break;
}
}
}

for (int i = 0; i < 2; i++)
{
if (Rectangle.Intersects(anotherRectangle))
{
characterStats.Velocity.X *= -1;
characterStats.Velocity.Y *= -1;
}
}

characterStats.position.X += Velocity.X;
characterStats.position.Y += Velocity.Y;


The problem with this, is that sometimes, after collision, when pressing button to go in opposite direction from the collided sprite, the character starts going inside the sprite, in the opposite direction to where the button should move him. I know, that it happens cause of that *= -1, but how do i prevent that?

I believe the problem with your collision is that the character's rectangle continues to be within the other rectangle.

And if that's the case, then the solution would be too figure out the intersection width/height and and subtract it from the character's position so that they are popped out of the rectangle when they intersect.

For the image below, the code would be something like:

for (/* every rectangle to potentially collide with */)
{
if (/* rectangle intersects character */)
{
/* calculate dx and dy */

characterStats.position.X -= dx;
characterStats.velocity.X *= -1;

/* do similar process for Y */
}
}