0
votes

I want to make a Platform object solid from every side so that the Player could not pass through it. I think the most simple idea is to use a "previous position" variable. Especially with the Intersects() method (I like it)!

If Player intersects, then move to last position. But nothing happens. Most likely I couldn't figure out how to implement proper "previous position".

Here's what I have in class Player:

public void Collision(Sprite obj)
    {
        Vector2 previousPosition = this.Position;
        if (this.Bounds.Intersects(obj.Bounds))
        {
            this.Position = previousPosition;
        }
    }

Player and Platform inherit Sprite class which has this property:

public Rectangle Bounds
{
    get
    {
       return new Rectangle((int)Position.X, (int)Position.Y,
                             Texture.Width, Texture.Height);
    }
}

Another idea I tried was to use a bool isSolid but I didn't know how to work the logic. I've searched and tried things around the net(including stackoverflow) for maybe 4-5 hours. This is supposed to be so simple, yet I can't understand it!

1

1 Answers

0
votes

The answer is simple. Take look at the previousPosition and you see the problem. I'm gonna explain the problem like this.

X is my current X • Prev X is my previous X • • I move forward in X axis so X increments by 1 • x is now 1 • prev X is now x (so it's basically 1)

x hits the object so x becomes = prev X

So basically x becomes itself everytime it checks if it's hitting the target.

Solution 1. Set the previousPosition variable to the currentPosition before you move, so currentPosition value changes and previousPosition is not the same as currentPosition everytime.

In short this is the order

  • set prevPos to playerPos
  • move the player
  • set currentPos to playerPos
  • check for colliding
  • set playerPos to prevPos if they did collide

EDIT: The code you provided does this:

PreviousPosition = this.Position;
this.Position = currentPosition;

First line is correct but the second line that you have in the collide function needs to be changed to

this.Position = previousPosition;

If that doesn't work there is an other solution. Regards, Tuukka.