3
votes

I am currently having trouble making a sprite appear solid using bounding boxes. The collisions work just fine with the code below.

Position is the main characters position on the map. character2 is the name of an 18 x 28 sprite that the main character will collide with.

When the main character collides with the character2 sprite, I have tried adjusting the position back accordingly (EX: Position.X -=1;) but this just slides my main sprite back until it does not intersect.

I have a feeling it's something very simple, but for the life of me, I just cannot figure it out.

To summarize my question: How do I make the character2 sprite appear solid upon collision?

Also, even if my main sprite stops upon the collision (By reducing speed to 0) it gets stuck there, the if statement entering an endless loop.

        float x1 = Position.X;
        float y1 = Position.Y;

        float x2 = x1 + character2.Width;
        float y2 = y1 + character2.Height;

        BoundingBox b1 = new BoundingBox(new Vector3(x1, y1, 0), 
            new Vector3(x2, y2, 0));
        BoundingBox b2 = new BoundingBox(new Vector3(Position2.X, Position2.Y, 0),
            new Vector3(x2, y2, 0));


        if (Collision(b1, b2))
        {
            // ????
        }
2

2 Answers

2
votes

It depends on what you want to happen exactly, but one suggestion is something like this...

  if (HorizontalCollision(b1, b2))
  {
    xv = -xv;
  }
  else if (VerticalCollision(b1, b2))
  {
    yv = -yv;
  }

  Position2.X += xv;
  Position2.Y += yv;

xv and yv would be velocity variables in this case and you're simply reversing their direction when there's a horizontal or vertical collision, respectively. This will cause the objects or characters to literally bounce off eachother.

You could then add xv *= .99 and yv *= .99 for the velocity to slow after every rendering loop, simulating momentum and friction. Lots of different possibilities open up when you utilize velocity variables like this. By the way, this is called Euler integration and is incredibly efficient for the purposes of animation.

0
votes
While(Collision(b1, b2))
{
    Position.X -=1;
}

Is that what you want? :P