1

I have do a collision with my map the collision work but when my player have a collision I stop the movement of the player and he don't walk because I don't know how stop the player for one direction

its my code collision under the player and the map

public bool IsCollisionTile(Rectangle player)
{
    foreach(Rectangle rect in this._collisionObject)
    {
        if (rect.Intersects(player))
        {
            return true;
        }
    }
    return false;
}

Its the code for the player don't move is in the Game1 class

if (mapLoader.IsCollisionTile(player.getDestinationRect()))
{
        player.setCantWalk(true);
}

Its the function update and setCantWalk in the class Player.cs

private bool _cantWalk;

    public void Update()
    {
    this._destinationRectangle.X = (int)_position.X;
    this._destinationRectangle.Y = (int)_position.Y;
    this._destinationRectangle.Width = _texture.Width;
    this._destinationRectangle.Height = _texture.Height;
    if(Keyboard.GetState().IsKeyDown(Keys.Up))
            {
                if (_cantWalk == false)
                {
                    _position.Y--;
                }
            }
            else if (Keyboard.GetState().IsKeyDown(Keys.Down))
            {
                if (_cantWalk == false)
                {
                    _position.Y++;
                }
            }
            else if (Keyboard.GetState().IsKeyDown(Keys.Right))
            {
                if (_cantWalk == false)
                {
                    _position.X++;
                }
            }
            else if (Keyboard.GetState().IsKeyDown(Keys.Left))
            {
                if (_cantWalk == false)
                {
                    _position.X--;
                }
            }

        }

        public void setCantWalk(bool walk)
        {
            _cantWalk = walk;
        }

Thinks to help me

  • You could try moving your player on the X axis, doing the collision check, then the Y axis and doing the check again, and reverting whichever one(s) cause the check... doesn't seem ideal, but it's an option – Callum Bradbury Mar 01 '17 at 13:11
  • Hello but I'm a beginner and I don't know how to do – TheYoungGeek 43 Mar 01 '17 at 13:52

1 Answers1

0

For the simpler approach, you need to keep the record of the movements of your objects. So, when checking for overlaps, you know what movement in a direction caused the overlap. Then, set the variable cantWalkX or cantWalkY for that object.

A better solution would be checking for collision surfaces to determine obstacles. This requires you to change your intersect routine to return the intersecting objects, and depending on their relative position, prevent movement in that direction. For example, if the colliding object is to the right of your object, Set cantWalkXPositive. If there is another on the left, set cantWalkXNegative to true etc...