Search code examples
c#xna

XNA - Make sprite unable to go out of borders


I've been playing a little around with MinX and MinY, but I simply can't make it work. I have this player( a box ), which I use my mouse to guide around. However I can cross the borders so the player can't be seen. I would like to fix that, but can't figure out how.

Heres my code ( I give you complete, since I am not sure what part of it you will need):

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace SquareGame
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        /// 


        Texture2D Player;
        Vector2 spritePosition = Vector2.Zero;
        private Vector2 origin;
        private Vector2 screenpos;
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            Player = Content.Load<Texture2D>("Models\\Player");
            Viewport viewport = graphics.GraphicsDevice.Viewport;
            origin.X = Player.Width / 2;
            origin.Y = Player.Height / 2;
            screenpos.X = viewport.Width / 2;
            screenpos.Y = viewport.Height / 2;



            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        private float RotationAngle;
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds * 2;

            // TODO: Add your update logic here

            RotationAngle += elapsed;
            float circle = MathHelper.Pi * 2;
            RotationAngle = RotationAngle % circle;;

            spritePosition.X = Mouse.GetState().X;
            spritePosition.Y = Mouse.GetState().Y;

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        ///

        protected override void Draw(GameTime gameTime)
        {
            graphics.GraphicsDevice.Clear(Color.LightGoldenrodYellow);

            // TODO: Add your drawing code here
            spriteBatch.Begin();
            spriteBatch.Draw(Player, spritePosition, null, Color.White, RotationAngle, origin, 1.0f, SpriteEffects.None, 0f);
            spriteBatch.End();


            base.Draw(gameTime);
        }
    }
}

And a picture of my player at the border: https://i.sstatic.net/uc9LI.jpg

Thank you in advance! :)


Solution

  • in your Update method say:

    if(Mouse.GetState().X > 0 && Mouse.GetState().X < yourWindowWidth)            
        spritePosition.X = Mouse.GetState().X;
    else if (Mouse.GetState().X < 0)
        spritePosition.X = 0;
    else                   //The mouse is out from the right side of the window.
        spritePosition.X = yourWindowWidth;
    if(Mouse.GetState().Y > 0 && Mouse.GetState().Y < yourWindowHeight)
        spritePosition.Y = Mouse.GetState().Y;
    else if (Mouse.GetState().Y < 0)
        spritePosition.Y = 0;
    else                   //The mouse is out from the bottom side of the window.
        spritePosition.Y = yourWindowHeight;
    

    hope this helps.