0
votes

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.

2
I think you will need to check the mouse position against each obstacle like: if (offsetPosition.X < obstacle.Left) { // The mouse is off to the left of the obstacle }. Of course, you will need to define for each obstacle if we should be checking above, below, left or right of it for the mouse. - user3256944 salutes Monica

2 Answers

1
votes

As you know, you can read the the mouse position by calling Mouse.GetState(). But you can also set the mouse position to whatever you want through Mouse.SetPosition(X,Y) and the mouse will go there.

So, if you are up against, say, an X barrier (vertical barrier), simply call

Mouse.SetPosition(oldMouseState.X, mState.Y);

and your mouse will not change its X value even if pushing your mouse in that direction, it will not go through the wall at all but it is allowed to go up and down just fine. If you back off from the wall, simply don't call this line and it will operate like befor.

1
votes

You could store the last (valid) known position of the mouse and the current position of the mouse (valid means the mouse isn't in a rectangle where it shouldn't be). When you hit a rectangle that the mouse shouldn't pass through with your current mouse position, you iterate back to the last valid position in a while loop and check if the mouse is still in the blocking sprite every time you moved the mouse closer to the valid position. If the mouse is outside the forbidden zone, you just exit the while loop and the mouse is quite close to the border of the obstacle.