Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to create a XNA maze game, but at the very beginning, I got a problem. Here's my Update method:
C#
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Escape))
    this.Exit();
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Left))
    ballPosition.X -= ballSpeed;
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Right))
    ballPosition.X += ballSpeed;
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Down))
    ballPosition.Y += ballSpeed;
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Up))
    ballPosition.Y -= ballSpeed;
if (ballPosition.X >= width)
    ballPosition.X = width;
if (ballPosition.X <= 0)
    ballPosition.X = 0;
if (ballPosition.Y >= height)
    ballPosition.Y = height;
if (ballPosition.Y <= 0)
    ballPosition.Y = 0;
base.Update(gameTime);

But, when I run the game, ball won't go out at x=0 or y=0, but at other points it goes out of my game screen.
P. S. width and height are specified in Initialize method with ballPosition default values:
MIDL
width = graphics.GraphicsDevice.Viewport.Width;
height = graphics.GraphicsDevice.Viewport.Height;
ballPosition.X = width / 2;
ballPosition.Y = height / 2;
Posted

1 solution

The reason the ball is going out of the screen is that the ball speed can be more then 1 as such you must check if the current position of the ball plus the ball speed goes out of screen and handle it (by setting its postion to width)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900