How to prevent "mouse object" from moving throgh rectangles?

Started by
1 comment, last by Stefan Fischlschweiger 8 years, 7 months ago

Hi,

What am I trying to achieve?

I have a Sprite which is supposed to move with the mouse position (kinda like a cursor). In my case though I also have some other Textures (Obstacle-class). So if the mouse collides with such an obstacle I want the texture to stop moving in that direction.

What is the problem?

While the texture does follow the mouse and also does stop when the mouse "collides" with an obstacle, at some point the cursor is not within the Bounding Rectangle anymore, but on the other side of a wall for example. The consequence, the texture's position is updated to the mouse position and it suddenly appears behind the wall which is not a desired behavior.

My collision method.


        private void CheckCollision(List<Obstacle> _obstacleList, MouseState mState)
        {
            int xOffset = oldMouseState.X - mState.X;
            int yOffset = oldMouseState.Y - mState.Y;

            Vector2 offsetPosition = new Vector2(oldMouseState.X + xOffset,oldMouseState.Y + yOffset);
            
            bool collides = false;

            foreach (Obstacle obstacle in _obstacleList)
            {
                if (obstacle.BoundRectangle.Contains(offsetPosition))
                {
                    collides = true;
                }
            }

            if (!collides)
            {
                position = offsetPosition;
            }
        }

Question

What be a way to prevent the sprite to move through walls in my case?

Thanks in advance.

Advertisement

I think what you're looking for is swept collision. You would "sweep" the box from the last known good object position to the box for the new mouse position:

This article might help you:

http://www.gamedev.net/page/resources/_/technical/game-programming/swept-aabb-collision-detection-and-response-r3084

It looks like you are trying to have the player move one object/sprite move around other objects/sprites (the obstacles) but you have bound the objects position directly to the mouse screen coordinates and each frame it tried to update it's position to where the mouse is.

What you need to do is use mouse delta (movement since last frame) instead of absolute coordinates.

Therefore (pseudocode)


moveplayer()
{
    var delta = GetMouseDelta();
    
    bool posValid = CheckNewPosition(playerPos, delta);

    if(posValid)
    {
        playerPos += delta; // Move player by delta;
    }
    else
    {
        playerPos = GetClosestPosition(playerPos, delta); // Move player to closest valid position.
    }
}

This topic is closed to new replies.

Advertisement