Difficulties with Windows Phone Accelerometer - c#

I want to use the accelerometer to move a ball in a Windows Phone game. But the ball moves not correct when I tilt the Windows Phone device.
For example, if I tilt the device to the left, the ball isn't moving to the left, instead the ball moves very strange. I don't know what I could change in my code so that the ball moves correctly.
What should I change so that the ball moves correctly if I tilt the Windows Phone device?
UPDATE:
I changed my code but the ball doesn't move in the right direction.
You can download my project here: http://www.file-upload.net/download-8439759/WindowsPhoneGame22.rar.html
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Motion motion;
Texture2D Ball;
Vector2 BallPos = new Vector2(400, 300);
Vector3 accelReading = new Vector3();
Vector3 speed = new Vector3();
void motion_CurrentValueChanged(object sender, SensorReadingEventArgs<MotionReading> e)
{
UpdateUI(e.SensorReading);
}
private void UpdateUI(MotionReading e)
{
accelReading.X = e.DeviceAcceleration.X;
accelReading.Y = e.DeviceAcceleration.Y;
accelReading.Z = e.DeviceAcceleration.Z;
accelReading.Normalize();
Vector3 currentAccelerometerState = accelReading;
if (currentAccelerometerState.X != 0)
speed += new Vector3(currentAccelerometerState.X, 0, 0);
if (currentAccelerometerState.Z != 0)
speed += new Vector3(0, 0, -currentAccelerometerState.Z);
if (speed.Length() > 2)
{
speed.Normalize();
speed *= 2;
}
BallPos.X += speed.X;
BallPos.Y += speed.Y;
}
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
TargetElapsedTime = TimeSpan.FromTicks(333333);
InactiveSleepTime = TimeSpan.FromSeconds(1);
graphics.IsFullScreen = true;
}
protected override void Initialize()
{
if (Motion.IsSupported)
{
motion = new Motion();
motion.TimeBetweenUpdates = TimeSpan.FromMilliseconds(20);
motion.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<MotionReading>>(motion_CurrentValueChanged);
motion.Start();
}
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
Ball = Content.Load<Texture2D>("ballbig");
}
protected override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(Ball, BallPos, null, Color.White, rotation, new Vector2(Ball.Width/2,Ball.Height/2), 1f, SpriteEffects.None,1);
spriteBatch.End();
base.Draw(gameTime);
}
}

I did a pretty similar game on Windows8, and I use a method like this to handle the accelerometer. I hope you can find something that can help you.
private Accelerometer _accelerometer;
public void Initialize()
{
if (_accelerometer != null)
{
_accelerometer = Accelerometer.GetDefault();
_accelerometer.ReadingChanged += _accelerometer_ReadingChanged;
}
}
private void _accelerometer_ReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args)
{
AccelerometerReading reading = _accelerometer.GetCurrentReading();
Vector3 stateValue = new Vector3();
stateValue.Y = -1;
stateValue.X = (float)reading.AccelerationX;
stateValue.Z = (float)reading.AccelerationY;
stateValue.Normalize();
Vector3 currentAccelerometerState = stateValue;
Vector3 Rotation = Vector3.Zero;
if (currentAccelerometerState.X != 0)
marble.speed += new Vector3(currentAccelerometerState.X, 0, 0);
if (currentAccelerometerState.Z != 0)
marble.speed += new Vector3(0, 0, -currentAccelerometerState.Z);
if (marble.speed.Length() > 10)
{
marble.speed.Normalize();
marble.speed *= 10;
}
}

Related

Camera is stuttering after random amount of time

I have a problem that my camera starts to stutter when moving it after a random amount of time. This is not the case for the movement itself. That runs really smoothly. It is just hte camera that starts to stutter. Small notice I am working in monogame
Here is the code of the main
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Cube_chaser
{
public class CubeChaserGame : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Camera camera;
Map map;
BasicEffect effect;
private Vector2 mouseRotationBuffer;
private MouseState currentMouseState, previousMouseState;
public Vector3 moveVector = Vector3.Zero;
public CubeChaserGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
camera = new Camera(this, new Vector3(0.5f, 0.5f, 0.5f), Vector3.Zero, 5f);
Components.Add(camera);
effect = new BasicEffect(GraphicsDevice);
map = new Map(GraphicsDevice);
IsMouseVisible = false;
graphics.IsFullScreen = true;
previousMouseState = Mouse.GetState();
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
KeyboardState keyState = Keyboard.GetState();
currentMouseState = Mouse.GetState();
moveVector = Vector3.Zero;
//Handle the mouse movement for rotation
float deltaX, deltaY;
if (currentMouseState != previousMouseState)
{
//We need to save the mouse location for further use
deltaX = (currentMouseState.X - (GraphicsDevice.Viewport.Width / 2));
deltaY = (currentMouseState.Y - (GraphicsDevice.Viewport.Height / 2));
mouseRotationBuffer.X -= (0.09f * deltaX * dt);
mouseRotationBuffer.Y -= (0.09f * deltaY * dt);
if (mouseRotationBuffer.Y < MathHelper.ToRadians(-75.0f))
{
mouseRotationBuffer.Y = mouseRotationBuffer.Y - (mouseRotationBuffer.Y - MathHelper.ToRadians(-75.0f));
}
if (mouseRotationBuffer.Y > MathHelper.ToRadians(75.0f))
{
mouseRotationBuffer.Y = mouseRotationBuffer.Y - (mouseRotationBuffer.Y - MathHelper.ToRadians(75.0f));
}
camera.Rotation = new Vector3(-MathHelper.Clamp(mouseRotationBuffer.Y, MathHelper.ToRadians(-75.0f), MathHelper.ToRadians(75.0f)), MathHelper.WrapAngle(mouseRotationBuffer.X), 0);
deltaX = 0;
deltaY = 0;
}
try { Mouse.SetPosition(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2); }
catch { }
if (keyState.IsKeyDown(Keys.W)) moveVector.Z = 1;
if (keyState.IsKeyDown(Keys.S)) moveVector.Z = -1;
if (keyState.IsKeyDown(Keys.A)) moveVector.X = 1;
if (keyState.IsKeyDown(Keys.D)) moveVector.X = -1;
if (keyState.IsKeyDown(Keys.Space) && camera.Position.Y >= 0.5f && camera.Position.Y <= 0.8f) moveVector.Y = 0.05f;
// if (camera.Position.Y == 0.8f&&camera.Position.Y>=0.5f)camera.moveVector.Y=-0.01f;
if (moveVector != Vector3.Zero)
{
//We don't want to make the player move faster when it is going diagonally.
moveVector.Normalize();
//Now we add the smoothing factor and speed factor
moveVector *= (dt * camera.cameraSpeed);
Vector3 newPosition = camera.PreviewMove(moveVector);
bool moveTrue = true;
if (newPosition.X < 0 || newPosition.X > Map.mazeWidth) moveTrue = false;
if (newPosition.Z < 0 || newPosition.Z > Map.mazeHeight) moveTrue = false;
foreach (BoundingBox boxes in map.GetBoundsForCell((int)newPosition.X, (int)newPosition.Z))
{
if (boxes.Contains(newPosition) == ContainmentType.Contains)
{
moveTrue = false;
}
}
if (moveTrue) camera.Move(moveVector);
previousMouseState = currentMouseState;
camera.Update(gameTime);
base.Update(gameTime);
}
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
map.Draw(camera, effect);
// TODO: Add your drawing code here
base.Draw(gameTime);
}
}
}
This is the code for the camera:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Graphics;
namespace Cube_chaser
{
public class Camera: GameComponent
{
#region Fields
public Vector3 cameraPosition;
public Vector3 cameraRotation;
public float cameraSpeed;
private Vector3 cameraLookAt;
#endregion
#region Properties
public Matrix Projection
{
get;
protected set;
}
public Matrix View
{
get
{
return Matrix.CreateLookAt(cameraPosition, cameraLookAt, Vector3.Up);
}
}
public Vector3 Position
{
get { return cameraPosition; }
set
{
cameraPosition = value;
UpdateLookAt();
}
}
public Vector3 Rotation
{
get { return cameraRotation; }
set
{
cameraRotation = value;
UpdateLookAt();
}
}
#endregion
#region Constructor
public Camera (Game game, Vector3 position, Vector3 rotation, float speed):base(game)
{
cameraSpeed = speed;
//Setup the projection Matrix
Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, game.GraphicsDevice.Viewport.AspectRatio, 0.05f, 100.0f);
MoveTo(position, rotation);
}
#endregion
#region Helper Methods
//Set the camera its position and rotation
public void MoveTo(Vector3 pos, Vector3 rot)
{
Position = pos;
Rotation = rot;
}
//Updating the look at vector
public void UpdateLookAt()
{
//Built a rotation matrix to rotate the direction we are looking
Matrix rotationMatrix = Matrix.CreateRotationX(cameraRotation.X) * Matrix.CreateRotationY(cameraRotation.Y);
// Build a look at offset vector
Vector3 lookAtOffset = Vector3.Transform(Vector3.UnitZ, rotationMatrix);
//Update our camera's look at the vector
cameraLookAt = (cameraPosition + lookAtOffset);
}
//Method to create movement and to check if it can move:)
public Vector3 PreviewMove(Vector3 amount)
{
//Create a rotation matrix to move the camera
Matrix rotate = Matrix.CreateRotationY(cameraRotation.Y);
//Create the vector for movement
Vector3 movement = new Vector3(amount.X, amount.Y, amount.Z);
movement = Vector3.Transform(movement, rotate);
// Give the value of the camera position +ze movement
return (cameraPosition+movement);
}
//Method that moves the camera when it hasnt'collided with anything
public void Move(Vector3 scale)
{
//Moveto the location
MoveTo(PreviewMove(scale), Rotation);
}
#endregion
/*public void Update(GameTime gameTime)
{
}*/
}
}
Any idea why the camera stutters after a while?
Thanks,
Jeromer
Forgot to post the answer to my problem for people having the same issue.
The following changes were made to make the problem go away:
in the constructor of the game1 class
IsFixedTimeStep = true;
TargetElapsedTime = TimeSpan.FromMilliseconds(16);
This results in fixed timesteps and thus a smooth calculation

(Xna) My players position won't update, I need it for my enemy to follow

enter code hereWhen im drawing it to a string it just stays at 300,300 . My mouse always updates its Vector2 position.X, position.Y. I need to be able to update my players position or my enemy wont follow my player. It just goes to that certain player position i set for it. PLEASE HELP AND THANK YOU!
class Enemy
{
Player p = new Player();
public Vector2 direction, velocity,position;
public float speed;
public Texture2D texture;
public Enemy()
{
speed = 1;
texture = null;
position = new Vector2(600, 500);
}
public void LoadContent(ContentManager Content)
{
texture = Content.Load<Texture2D>("circle");
}
public void Update(GameTime gameTime)
{
MouseState mouse = Mouse.GetState();
direction = p.position - position;
direction.Normalize();
velocity = direction * speed;
position += velocity;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, position, Color.Red);
}
/*
direction = p.position - position;
direction.Normalize();
velocity = direction * speed;
position += velocity;
*/
}
class Player
{
public float rotation, bulletDelay;
public Vector2 position,velocity,origin;
public string spriteName;
public Texture2D texture,bulletTexture;
List<Bullets> bullets = new List<Bullets>();
public float speed = 10;
public float health = 100;
public Player()
{
texture = null;
spriteName = "playerover";
position = new Vector2(300, 300);
bulletDelay = 20;
}
public void LoadContent(ContentManager Content)
{
texture = Content.Load<Texture2D>(spriteName);
bulletTexture = Content.Load<Texture2D>("playerbullet");
}
public void Draw(SpriteBatch spriteBatch)
{
origin = new Vector2(texture.Width / 2, texture.Height / 2);
spriteBatch.Draw(texture, new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height), null, Color.White, rotation,new Vector2(texture.Width / 2, texture.Height / 2), SpriteEffects.None, 0);
foreach (Bullets bullet in bullets)
{
bullet.Draw(spriteBatch);
}
}
public void Update(GameTime gameTime)
{
MouseState curMouse = Mouse.GetState();
KeyboardState keyState = Keyboard.GetState();
Vector2 mouseLoc = new Vector2(curMouse.X, curMouse.Y);
Vector2 direction = mouseLoc - position;
rotation = (float)(Math.Atan2(direction.Y, direction.X));
if (keyState.IsKeyDown(Keys.W))
{
position.Y -= speed;
}
if (keyState.IsKeyDown(Keys.S))
{
position.Y += speed;
}
if (keyState.IsKeyDown(Keys.A))
{
position.X -= speed;
}
if (keyState.IsKeyDown(Keys.D))
{
position.X += speed;
}
if (curMouse.LeftButton == ButtonState.Pressed)
{
Shoot();
}
UpdateBullets();
}
public void UpdateBullets()
{
foreach (Bullets bullet in bullets)
{
bullet.position += bullet.velocity;
if (bullet.position.Y <= 5)
{
bullet.isVisible = false;
}
if (bullet.position.X <= 5)
{
bullet.isVisible = false;
}
if (bullet.position.X >= 785)
{
bullet.isVisible = false;
}
if (bullet.position.Y >= 575)
{
bullet.isVisible = false;
}
}
for (int i = 0; i < bullets.Count; i++)
{
if (!bullets[i].isVisible)
{
bullets.RemoveAt(i);
i--;
}
}
}
public void Shoot()
{
if (bulletDelay >= 0)
bulletDelay--;
if (bulletDelay <= 0)
{
Bullets newBullet = new Bullets(bulletTexture);
newBullet.velocity = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) * 5f + velocity;
newBullet.position = position + newBullet.velocity * 5;
newBullet.isVisible = true;
if (bullets.Count < 20)
{
bullets.Add(newBullet);
}
}
if (bulletDelay == 0)
{
bulletDelay = 20;
}
}
}
class Hud
{
public SpriteFont font;
public bool showHud;
Player p = new Player();
Enemy e = new Enemy();
public Hud()
{
showHud = true;
}
public void LoadContent(ContentManager Content)
{
font = Content.Load<SpriteFont>("font");
}
public void Draw(SpriteBatch spriteBatch)
{
MouseState mouse = Mouse.GetState();
if (showHud)
{
spriteBatch.DrawString(font, "Mouse.X = " + mouse.X, new Vector2(10, 0), Color.White);
spriteBatch.DrawString(font, "Mouse.Y = " + mouse.Y, new Vector2(10, 20), Color.White);
spriteBatch.DrawString(font, "Health = " + p.health, new Vector2(10, 40), Color.White);
spriteBatch.DrawString(font, "Pos.Y = " + p.position.Y, new Vector2(10, 60), Color.White);
spriteBatch.DrawString(font, "Pos.X = " + p.position.X, new Vector2(10, 80), Color.White);
}
}
}
I didn't read all the code you posted, but it seems that you created a new separate instance for the player in the Enemy class which is never updated.
class Enemy
{
Player p = new Player();
//...
}
You should either take a Vector2 for the players position into your enemies Update method or handle the enemy movement somewhere else. Perhaps you could have a method in your Enemy class named Follow taking a Player object as a parameter, then you could do something like the following in the place where you handle all entity movement. It would look roughly like this:
public void UpdateEntities(GameTime gameTime)
{
player.Update(gameTime);
enemy.Update(gameTime);
if(PlayerDistanceFromEnemy() < 50)
enemy.Follow(player);
}
That is a very rough guideline and probably something you'd want to rewrite later on, but it will work.
as for the Follow method in your enemy class:
public void Follow(Player player)
{
this.p = player;
}
public void Update(GameTime gameTime)
{
if(p != null)
{
//do stuff
}
}
This will work, but you have to work on the structure of your code if you want to expand. I might update this answer later with a better solution if someone doesn't do it before me.

How do i check if there are no key inputs on xna

public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D walkRight, walkUp, walkLeft, walkDown, currentWalk, TitleScreen, stand;
Rectangle destRect;
Rectangle sourceRect;
KeyboardState ks;
Vector2 position = new Vector2();
bool isGrounded;
bool isStanding;
float fallSpeed = 5;
enum GameStates { Titlescreen, Playing, PlayerDead, GameOver };
GameStates gameStates = GameStates.Titlescreen;
float elapsed;
float delay = 200f;
int frames = 0;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
destRect = new Rectangle(50, 50, 50, 50);
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
walkRight = Content.Load<Texture2D>("walkRight");
walkUp = Content.Load<Texture2D>("walkUp");
walkLeft = Content.Load<Texture2D>("walkLeft");
walkDown = Content.Load<Texture2D>("walkDown");
TitleScreen = Content.Load<Texture2D>("TitleScreen");
stand = Content.Load<Texture2D>("SpriteStill");
currentWalk = walkRight;
}
protected override void UnloadContent()
{
}
private void Animate(GameTime gameTime)
{
elapsed += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if (elapsed >= delay)
{
if (frames >= 3)
{
frames = 0;
}
else
{
frames++;
}
elapsed = 0;
}
sourceRect = new Rectangle(50 * frames, 0, 50, 50);
}
protected override void Update(GameTime gameTime)
//{
//switch (gameStates)
{
if (position.Y >= Window.ClientBounds.Height - 50)
{
position.Y = Window.ClientBounds.Height - 50;
isGrounded = true;
}
if (position.X >= Window.ClientBounds.Width - 50)
{
position.X = Window.ClientBounds.Width - 50;
}
if (position.X <=0)
{
position.X = 0;
}
if (position.Y <= 0)
{
position.Y = 0;
}
ks = Keyboard.GetState();
if (ks.IsKeyDown(Keys.Right))
{
position.X += 3f;
currentWalk = walkRight;
}
if (ks.IsKeyDown(Keys.Left))
{
position.X -= 3f;
currentWalk = walkLeft;
}
if (ks.IsKeyDown(Keys.Down))
{
position.Y += 3f;
currentWalk = walkDown;
}
Animate(gameTime);
destRect = new Rectangle((int)position.X, (int)position.Y, 50, 50);
FallManagement(gameTime);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(currentWalk, destRect, sourceRect, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
void FallManagement(GameTime gameTime)
{
position.Y += fallSpeed;
if (isGrounded == false)
{
fallSpeed = 5;
}
if (ks.IsKeyDown(Keys.Up) && isGrounded)
{
fallSpeed -= 40;
isGrounded = false;
}
}
}
I am currently creating a very basic XNA platform game for a year one college course. I am currently trying to add in a statement that says if no keys are pressed then load up texture 2d for the character standing still, but I'm not sure how to check if the there are no keys pressed at all. Basically I would like to check if the character is moving and if not the texture for the character would be set to the standing still png, does anyone know how I might do this. I have put the entire code into this question because I am not using a character class and my level of coding is extremely basic at current.
Maybe something like this would work for you:
ks = Keyboard.GetState();
bool isMoving = false;
if (ks.IsKeyDown(Keys.Right))
{
position.X += 3f;
currentWalk = walkRight;
isMoving = true;
}
if (ks.IsKeyDown(Keys.Left))
{
position.X -= 3f;
currentWalk = walkLeft;
isMoving = true;
}
if (ks.IsKeyDown(Keys.Down))
{
position.Y += 3f;
currentWalk = walkDown;
isMoving = true;
}
if (!isMoving)
{
//Do whatever you need to do when the player is still here
}
Basically set a flag when any key is pressed that you handle, and then use that flag later to do what you need to do when no key is pressed.
Or, if you want to check that no key is pressed what-so-ever:
if (ks.GetPressedKeys() == null || ks.GetPressedKeys().Length == 0)
{
//No keys pressed at all. (not sure if GetPressedKeys returns null
//or zero length array, check when in debug then remove one.
}

Ping pong game: ball bounces like crazy

I am very new to C# and XNA and well.. just new to programming in general as well.
So, as an assignment, I need to make a ping pong game using xna.
I was doing alright until I realized that the ball bounces like crazy on the bottom of the screen for a reason that I cannot identify.
Below is my code
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 PongGame
{
public class Game1 : Microsoft.Xna.Framework.Game
{
SpriteFont score;
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D leftPaddle;
Texture2D rightPaddle;
Texture2D centerLine;
private Texture2D ball;
private Vector2 leftPaddlePosition = new Vector2();
private Vector2 rightPaddlePosition = new Vector2();
private Vector2 centerLinePosition = new Vector2();
private Vector2 ballPosition = new Vector2();
private Vector2 ballVelocity = new Vector2();
private int WIDTH, HEIGHT;
private int scoreOne=0;
private int scoreTwo=0;
private int round = 1;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
WIDTH = GraphicsDevice.Viewport.Width;
HEIGHT = GraphicsDevice.Viewport.Height;
leftPaddlePosition = new Vector2(0, (HEIGHT / 2)-40);
rightPaddlePosition = new Vector2(WIDTH-30, (HEIGHT / 2)-40);
centerLinePosition = new Vector2(WIDTH / 2, 0);
ballPosition = new Vector2((WIDTH / 2)-15, (HEIGHT / 2)-15);
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
leftPaddle = new Texture2D(GraphicsDevice, 1, 1);
leftPaddle.SetData(new[] { Color.White });
rightPaddle = new Texture2D(GraphicsDevice, 1, 1);
rightPaddle.SetData(new[] { Color.White });
centerLine = new Texture2D(GraphicsDevice, 1, 1);
centerLine.SetData(new[] { Color.White });
score = Content.Load<SpriteFont>("score1");
ball = Content.Load<Texture2D>("ball2");
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
if (round % 2 != 0)
//when the round is an odd numbered round,
{
ballVelocity = new Vector2(4f, 4f);
}
else if (round % 2 == 0)
{
ballVelocity = new Vector2(-4f, 4f);
}
KeyboardState key;
key = Keyboard.GetState();
if (key.IsKeyDown(Keys.W))
{
leftPaddlePosition.Y -= 5f;
}
if (key.IsKeyDown(Keys.S))
{
leftPaddlePosition.Y += 5f;
}
if (key.IsKeyDown(Keys.Up))
{
rightPaddlePosition.Y -= 5f;
}
if (key.IsKeyDown(Keys.Down))
{
rightPaddlePosition.Y += 5f;
}
//Left paddle manipulation
if (leftPaddlePosition.Y < 0)
{
leftPaddlePosition.Y = 0;
}
if (leftPaddlePosition.Y > HEIGHT-80)
{
leftPaddlePosition.Y = HEIGHT-80;
}
//Right paddle manipulation
if (rightPaddlePosition.Y < 0)
{
rightPaddlePosition.Y = 0;
}
if (rightPaddlePosition.Y > HEIGHT - 80)
{
rightPaddlePosition.Y = HEIGHT - 80;
}
//Making sure that the ball stays within the window
if (ballPosition.Y >= HEIGHT - 30)
{
ballVelocity.Y *= -1;
}
if (ballPosition.Y <= 0)
{
ballVelocity.Y *= -1;
}
//Checking if the ball goes over the left gutter
if (ballPosition.X < 29.9f)
{
ballPosition.X = 29.9f;
ballVelocity = new Vector2(0, 0);
scoreTwo++;
round++;
Initialize();
}
//Checking if the ball goes over the right gutter
if (ballPosition.X > WIDTH - 29.9f-29.9f)
{
ballPosition.X = WIDTH - 29.9f-29.9f;
ballVelocity = new Vector2(0, 0);
scoreOne++;
round++;
Initialize();
}
ballPosition.X += ballVelocity.X;
ballPosition.Y += ballVelocity.Y;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin();
spriteBatch.Draw(ball, ballPosition, Color.White);
spriteBatch.Draw(leftPaddle, leftPaddlePosition, null, Color.White, 0f, Vector2.Zero, new Vector2(30f, 80f), SpriteEffects.None, 0f);
spriteBatch.Draw(rightPaddle, rightPaddlePosition, null, Color.White, 0f, Vector2.Zero, new Vector2(30f, 80f), SpriteEffects.None, 0f);
spriteBatch.Draw(centerLine, centerLinePosition, null, Color.White, 0f, Vector2.Zero, new Vector2(1f, HEIGHT), SpriteEffects.None, 0f);
spriteBatch.DrawString(score, System.Convert.ToString(scoreOne), new Vector2(WIDTH/4-10, 10f), Color.White);
spriteBatch.DrawString(score, System.Convert.ToString(scoreTwo), new Vector2((WIDTH/4)*3-10, 10f), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
I understand that it is quite a long code to post here but since I don't know where the problem lies, I thought it would be best asking you guys.
I also uploaded the game to a dropbox account.
download link on dropbox
Without actually running the code I couldn't tell but SO is not here to write your code for you.
If it were me I would look at this bit here (seems like the most obvious suspect at a glance) ...
//Making sure that the ball stays within the window
if (ballPosition.Y >= HEIGHT - 30)
{
ballVelocity.Y *= -1;
}
if (ballPosition.Y <= 0)
{
ballVelocity.Y *= -1;
}
You should multiply the speed vectors by the amount of milliseconds sience the last frame divide by some speed constant (around 200).
This time is contained by the updatemethond's argument gameTime.

Having Difficulties Implementing Bullet/Enemy Collision Detection In A Simple Shooter (C# 2010/XNA 4.0)

Firstly, I would like to say sorry for making another thread asking the same question (more or less), but I am desperate for an answer and the other thread went dead.
I am currently working on a project for school in which I am attempting to make a simple 2d shooter. Problem is, I don't know how to implement collision detection between my two lists (being bullets and enemies as stated in title). I am very new to programming and have been using various tutorials as a guide, some tutorials say to use a nested for loop and if statement while I have seen others using an if statement, oh and I'm using the rectangle collision method not the pixel by pixel one I think it was called. Thanks in advance! :)
Here is my code:
Main:
namespace Software_Design_Major_Project
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D ship; // Declaring the sprite
Vector2 shipposition = Vector2.Zero; // Creating a vector for the sprite.
List<bullets> bullets = new List<bullets>(); // a list is created here so that there can be multiple copies of this item at once without writing the extra code.
Texture2D texture;
KeyboardState pastkey;
//bullet sound effect.
SoundEffect effect;
List<enemies> Enemies = new List<enemies>();
Random random2 = new Random();
float spawn = 0;
public enum GameState
{
MainMenu,
Playing,
}
GameState CurrentGameState = GameState.MainMenu;
int screenWidth = 600, screenHeight = 480;
cButton play;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
//changes width of screen to 600px.
graphics.PreferredBackBufferWidth = 600;
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
// This statement positions the ship.
ship = Content.Load<Texture2D>("ship"); // Loads the ship into the memory.
shipposition = new Vector2((graphics.GraphicsDevice.Viewport.Width / 2) - (ship.Width / 2), 420);
// loads bullet sprite
texture = Content.Load<Texture2D>("bullet");
graphics.PreferredBackBufferWidth = screenWidth;
graphics.PreferredBackBufferHeight = screenHeight;
graphics.ApplyChanges();
IsMouseVisible = true;
play = new cButton(Content.Load<Texture2D>("play"), graphics.GraphicsDevice);
play.setPosition(new Vector2(225, 220));
effect = Content.Load<SoundEffect>("laser");
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
spawn += (float)gameTime.ElapsedGameTime.TotalSeconds;
// spawns enemy every second.
foreach (enemies enemy in Enemies)
enemy.update(graphics.GraphicsDevice);
MouseState mouse = Mouse.GetState();
switch (CurrentGameState)
{
case GameState.MainMenu:
if (play.isClicked == true)
CurrentGameState = GameState.Playing;
play.Update(mouse);
break;
case GameState.Playing:
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.E))
{
Exit();
}
break;
}
// Allows the ship to move left and stops the ship going off the screen.
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Left) && shipposition.X >= 0)
{
shipposition.X -= 7;
}// same as above except for the right direction.
if (Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Right) && shipposition.X < ((graphics.GraphicsDevice.Viewport.Width) - (ship.Width)))
{
shipposition.X += 7;
}
// this prevents the player from holding down space to spam bullets.
if (Keyboard.GetState().IsKeyDown(Keys.Space) && pastkey.IsKeyUp(Keys.Space))
{
bullets bullet = new bullets(texture);
// the ships coordinates are gathered from the top left hand corner of the sprites rectangle therefore 'new Vector2(shipposition.X + 32, shipposition.Y)' had to
// be added rather than just = 'shipposition' to avoid having the bullets shoot from the wing.
bullet.position = new Vector2(shipposition.X + 32, shipposition.Y);
bullets.Add(bullet);
effect.Play();
}
pastkey = Keyboard.GetState();
//calls upon the update method from the bullets class.
foreach (bullets bullet in bullets)
bullet.update();
LoadEnemies();
base.Update(gameTime);
}
public void LoadEnemies()
{
int randX = random2.Next(10, 540);
if (spawn <= 1)
{
spawn = 0;
//limits amount of enemies on screen to 5.
if (Enemies.Count() < 5)
Enemies.Add(new enemies(Content.Load<Texture2D>("enemy"), new Vector2(randX, -100)));
}
for (int i = 0; i < Enemies.Count; i++)
{
if (!Enemies[i].enemyVisble)
{
//removes the enemies when they go off screen.
Enemies.RemoveAt(i);
i--;
}
}
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// calls draw method in bullets class
foreach (bullets bullet in bullets)
{
bullet.Draw(spriteBatch);
}
spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
spriteBatch.Draw(ship, shipposition, Color.White); // draws ship sprite
switch (CurrentGameState)
{
case GameState.MainMenu:
play.draw(spriteBatch);
spriteBatch.Draw(Content.Load<Texture2D>("menu"), new Rectangle(0, 0, screenWidth, screenHeight), Color.White);
break;
case GameState.Playing:
break;
}
foreach (enemies enemy in Enemies)
{
enemy.draw(spriteBatch);
}
spriteBatch.End();
base.Draw(gameTime);
}
}
}
Bullets Class:
namespace Software_Design_Major_Project
{
class bullets // A new class needs to be created to allow for bullets.
{
public Texture2D texture;
public Vector2 position;
public bool isvisible;
public bullets(Texture2D newtexture)
{
texture = newtexture;
isvisible = false;
}
public void update()
{
position.Y -= 3; // velocity of the bullet
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Begin();
spriteBatch.Draw(texture, position, Color.White);
spriteBatch.End();
}
}
}
Enemies Class:
namespace Software_Design_Major_Project
{
public class enemies
{
public Texture2D enemyTexture;
public Vector2 enemyPosition;
public bool enemyVisble = true;
public float enemyMoveSpeed;
public int Value;
Random random = new Random();
int randY;
public enemies (Texture2D newEnemyTexture, Vector2 newEnemyPosition)
{
enemyTexture = newEnemyTexture;
enemyPosition = newEnemyPosition;
randY = random.Next(1, 4);
enemyMoveSpeed = randY;
enemyVisble = true;
Value = 100;
}
public void update(GraphicsDevice graphics)
{
enemyPosition.Y += enemyMoveSpeed;
if (enemyPosition.Y > 500)
enemyVisble = false;
}
public void draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(enemyTexture, enemyPosition, Color.White);
enemyVisble = true;
}
}
}
You have several ways to do it... one of them maybe add a radio property to enemies and bullets....
for (int bi=0; bi<bullets.count; )
{
bool should_destroy_bullet = false;
Bullet b = bullets[bi];
for (int ei=0; ei<enemies.count; )
{
Enemy e = ememies[ei];
if (b.radio + e.radio < Vector2.Distance(b.Pos, e.Pos)) // Check collision
{
e.Died();
enemies[ei] = enemies[enemies.Count-1];
enemies.RemoveAt(enemies.Count-1);
should_destroy_bullet = true; // This lets a bullet kill more than one enemy
} else ei++;
}
if (should_destroy_bullet) {
b.Died();
bullets[bi] = bullets[bullets.count-1];
bullets.RemoveAt(bullets.count-1);
} else bi++;
}
Or you can build a rectangle for each sprite and check if they intersects....
if (b.Bounds.Intersects(e.Bounds)) ....
The Pythagorean theorem could work for you.(A squared plus B squared = C squared)
Make your players and enemies have a radius.Put this in your constructor.
public float radius = 15;
Put the following in a update void/subclass so that it happens every second.
Make a float the X location of your player and subtract the X location of the bullet. Square it.
float XDist = Math.Pow(player1.location.X - bullet.location.X,2);
Make a float the Y location of your player and subtract the Y location of the bullet.Square it.
float YDist = Math.Pow(player1.location.X - bullet.location.X,2);
Make a float to figure out the square root of the sum of Xdist and Ydist.
float actualDist = Math.Sqrt(Xdist + Ydist);
Now if the radius of your player is less than the distance between the player and the bullet, the bullet has hit the player.
if(actualDist < radius)
bullethit == true;

Categories