XNA Switch Statement Error - c#

I'm new to Xna and I'm trying to make an rpg. I built my game and received an error in my main game class. I'm getting errors from the Draw method of my code. I'm not used to using switch statements and I'm not sure what the proper way to make one is. What steps can I take to solve my error? Thanks.
error:
On the line: "switch (activeScreen)"
A switch expression or case label must be a bool, char, string,
integral, enum, or corresponding nullable type
Game Class:
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont font;
KeyboardState keyboardState;
KeyboardState oldKeyboardState;
GameScreen activeScreen;
StartScreen startScreen;
ActionScreen actionScreen;
CharScreen charScreen;
ClassScreen classScreen;
GenderScreen genderScreen;
Vector2 charPosition = new Vector2(0, 0);
Texture2D charSprite;
int charHorizSpeed = 1;
int charVertSpeed = 1;
Texture2D logoTexture;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.IsFullScreen = false;
oldKeyboardState = Keyboard.GetState();
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
charSprite = this.Content.Load<Texture2D>("charSprite");
//create new instance of the startScreen
startScreen = new StartScreen(
this,
spriteBatch,
//loads the font to the screen
font = Content.Load<SpriteFont>("menufont"),
//loads the image to the screen
Content.Load<Texture2D>("RPGLogo"));
//adds the screen to components
Components.Add(startScreen);
//startScreen.Hide();
//creates new instance the actionScreen
actionScreen = new ActionScreen(
this,
spriteBatch,
Content.Load<Texture2D>("tileMap"),
Content.Load<Texture2D>("character"),
charSprite = Content.Load<Texture2D>("charSprite"));
//adds the screen to components
Components.Add(actionScreen);
//actionScreen.Hide();
activeScreen.Hide();
activeScreen = startScreen;
activeScreen.Show();
charScreen = new CharScreen(
this,
spriteBatch,
charSprite = Content.Load<Texture2D>("charSprite"),
font = Content.Load<SpriteFont>("menufont"));
Components.Add(charScreen);
//charScreen.Hide ();
activeScreen.Hide();
activeScreen = charScreen;
activeScreen.Show();
classScreen = new ClassScreen(
this,
spriteBatch,
charSprite = Content.Load<Texture2D>("charSprite"),
font = Content.Load<SpriteFont>("menufont"));
Components.Add(classScreen);
activeScreen.Hide();
activeScreen = classScreen;
activeScreen.Show();
}
protected override void Update(GameTime gameTime)
{
//get hte current state of the keyboard
keyboardState = Keyboard.GetState();
UpdateSprite(gameTime);
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
//checks if instances are the same
if (activeScreen == startScreen)
{
//checks if enter key was pressed
if (CheckKey(Keys.Enter))
{
//if the selected index is on the first item (start game), the current active screen will hide adn it will be switched to the action screen
if (startScreen.SelectedIndex == 0)
{
activeScreen.Hide();
activeScreen = actionScreen;
activeScreen.Show();
}
//if the selected index is on the second item (exit) the game will exit
if (startScreen.SelectedIndex == 1)
{
this.Exit();
}
}
}
if (activeScreen == charScreen)
{
if (CheckKey(Keys.Enter))
{
if (charScreen.SelectedIndex == 0)
{
activeScreen.Hide();
activeScreen = classScreen;
activeScreen.Show();
//create a drop down menu for character class options/pop up?
}
}
if (CheckKey(Keys.Enter))
{
if (charScreen.SelectedIndex == 1)
{
activeScreen.Hide();
activeScreen = genderScreen;
activeScreen.Show();
}
}
}
if (activeScreen == classScreen)
{
if (CheckKey(Keys.Enter))
{
if (classScreen.SelectedIndex == 0)
{
//call warior class
}
if (classScreen.SelectedIndex == 1)
{
//call mage class
}
if (classScreen.SelectedIndex == 2)
{
//call ranger class
}
}
}
if (activeScreen == genderScreen)
{
if (CheckKey(Keys.Enter))
{
if (genderScreen.SelectedIndex == 0)
{
//call gender class (male)
}
if (genderScreen.SelectedIndex == 1)
{
//call gender class (female)
}
}
}
base.Update(gameTime);
oldKeyboardState = keyboardState;
}
private bool CheckKey(Keys theKey)
{
//returns if the key was pressed in the last frame
return keyboardState.IsKeyUp(theKey) &&
oldKeyboardState.IsKeyDown(theKey);
}
private void DrawStartScreen()
{
spriteBatch.DrawString(font, "Vengence In Albion", new Vector2(20, 45), Color.White);
}
private void DrawCharScreen()
{
spriteBatch.DrawString(font, "Character Selection", new Vector2(20, 45), Color.White);
spriteBatch.Draw(charSprite, charPosition, Color.White);
}
private void DrawClassScreen()
{
spriteBatch.DrawString(font, "Choose your Class", new Vector2(20, 45), Color.White);
}
private void DrawGenderScreen()
{
spriteBatch.DrawString(font, "Choose a gender", new Vector2(20, 45), Color.White);
}
private void UpdateSprite(GameTime gameTime)
{
//move the sprite by speed
KeyboardState newState = Keyboard.GetState();
int MaxX = Window.ClientBounds.Width - charSprite.Width;
int MaxY = Window.ClientBounds.Height - charSprite.Height;
int MinX = 0;
int MinY = 0;
if (newState.IsKeyDown(Keys.Left))
{
// Move left
charHorizSpeed = -1;
}
if (newState.IsKeyDown(Keys.Right))
{
// Move left
charHorizSpeed = 1;
}
if (newState.IsKeyDown(Keys.Up))
{
// Move left
charVertSpeed = -1;
}
if (newState.IsKeyDown(Keys.Down))
{
// Move left
charVertSpeed = 1;
}
if (charPosition.X > MaxX)
{
charHorizSpeed *= -1;
charPosition.X = MaxX;
}
else if (charPosition.X < MinX)
{
charHorizSpeed *= -1;
charPosition.X = MinX;
}
if (charPosition.Y > MaxY)
{
charVertSpeed *= -1;
charPosition.Y = MaxY;
}
else if (charPosition.Y < MinY)
{
charVertSpeed *= -1;
charPosition.Y = MinY;
}
oldKeyboardState = keyboardState;
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.DarkSlateBlue);
spriteBatch.Begin();
switch (activeScreen)
{
case activeScreen.startScreen:
DrawStartScreen();
StartScreen();
break;
case activeScreen.charScreen:
DrawCharScreen();
CharScreen();
break;
case activeScreen.actionScreen:
//draw map
break;
case activeScreen.classScreen:
DrawClassScreen();
ClassScreen();
break;
case activeScreen.genderScreen:
DrawGenderScreen();
GenderScreen();
break;
}
base.Draw(gameTime);
spriteBatch.End();
}
}

Without seeing types it is hard to tell, but activeScreen is definitely not a type you can use as a switch. Also, it looks like you are repeating the same methods in every case. According to the code above you don't need a switch statement at all.
Use a different method of determining the current screen like activeScreen is activeScreen.startScreen or something within if blocks..

Related

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.
}

Object reference is not set to an object

I am trying to create collision between my bullets and the enemy. I have created bounding boxes for each and placed them into their own class. However, I am getting a Null reference error in my HandleCollision function, specifically at the if statement with the bounding boxes. I will also post the rest of my code.
I discussed this with two lecturers and some peers and they asy it is because bullet and enemy are equal to null. This is because it takes a couple of seconds for the enemy to spawn and the bullet only spawns once it is fired. To counter this I added an if statement to check if the bullet or enemy is null yet it still throws up the same error.
HandleCollision Function
private void HandleCollision()//collision
{
Sprite toRemove = null;
if (bullet != null || enemyTexture != null)
{
foreach (EnemySprite e in enemyList) //checks each enemy sprite
{
if (bullet.BoundingBox.Intersects(enemy.BoundingBox))
{
enemyList.Remove(enemy); //removes enemy
//toRemove = enemy;
break;
}
}
}
}
Game1.cs
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Rectangle spriteRectangle;
Rectangle bulletBounds;
Rectangle enemyBounds;
Sprite player;
Bullets bullet;
EnemySprite enemy;
Texture2D enemyTexture;
List<EnemySprite> enemyList = new List<EnemySprite>();
List<Bullets> bulletsList = new List<Bullets>();
//Pause
bool paused = false;
Texture2D pauseTexture;
Rectangle pauseRectangle;
KeyboardState pastKey;
Vector2 enemyPos = new Vector2(100, 400);
Vector2 Position;
Vector2 Distance;
Vector2 spriteOrigin;
Vector2 spriteVelocity;
const float tangentialVelocity = 5f;
float friction = 0.1f;
float rotation;
float timer = 0f;
float dropInterval = 2f;
float speed = 4f;
float angle;
Random random;
enum GameState
{
MainMenu,
Options,
Help,
Playing,
Exit,
}
GameState CurrentGameState = GameState.MainMenu;
// Screen adjustments
int screenWidth = 800, screenHeight = 600;
cButton btnPlay;
cButtonExit btnExit;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
random = new Random();
Position = new Vector2(150, 150);
this.IsMouseVisible = true;
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
player = new Sprite();
player.Texture = Content.Load<Texture2D>("graphics/player");
// Screen stuff
graphics.PreferredBackBufferWidth = screenWidth;
graphics.PreferredBackBufferHeight = screenHeight;
//graphics.IsFullScreen = true;
graphics.ApplyChanges();
IsMouseVisible = true;
btnPlay = new cButton(Content.Load<Texture2D>("Graphics/play"), graphics.GraphicsDevice);
btnPlay.setPosition(new Vector2(350, 190));
btnExit = new cButtonExit(Content.Load <Texture2D>("Graphics/exit"), graphics.GraphicsDevice);
btnExit.setPosition(new Vector2(350, 220));
enemyTexture = Content.Load<Texture2D>("graphics/enemy");
player.Texture = Content.Load<Texture2D>("Graphics/player");
int screenCenterX = GraphicsDevice.Viewport.Width / 2;
player.Position = new Vector2(screenCenterX - (player.Texture.Width / 2), screenHeight - player.Texture.Height - 20);
pauseTexture = Content.Load<Texture2D>("graphics/paused");
pauseRectangle = new Rectangle(0, 0, pauseTexture.Width, pauseTexture.Height);
Bullets.BulletTexture = Content.Load<Texture2D>("graphics/bullet");
}
protected override void Update(GameTime gameTime)
{
MouseState mouse = Mouse.GetState();
IsMouseVisible = true;
switch (CurrentGameState)
{
case GameState.MainMenu:
if (btnPlay.isClicked == true) CurrentGameState = GameState.Playing;
btnPlay.Update(mouse);
if (btnExit.isClicked == true) CurrentGameState = GameState.Help;
btnExit.Update(mouse);
if (btnExit.isClicked == true) CurrentGameState = GameState.Options;
btnExit.Update(mouse);
if (btnExit.isClicked == true) CurrentGameState = GameState.Exit;
btnExit.Update(mouse);
break;
case GameState.Playing:
timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (timer >= dropInterval)
{
int yPos = random.Next(GraphicsDevice.Viewport.Height - 50);
enemyList.Add(new EnemySprite(enemyTexture, new Vector2(GraphicsDevice.Viewport.Width + 100, yPos)));
timer = 0f;
}
HandleCollision();
HandleMovingEnemy();
MouseState curMouse = Mouse.GetState();
Vector2 mouseLoc = new Vector2(curMouse.X, curMouse.Y);
Vector2 direction = mouseLoc - Position;
spriteRectangle = new Rectangle((int)Position.X, (int)Position.Y,
player.Texture.Width, player.Texture.Height);
Position = spriteVelocity + Position;
spriteOrigin = new Vector2(spriteRectangle.Width / 2, spriteRectangle.Height / 2);
Distance.X = mouse.X - Position.X;
Distance.Y = mouse.Y - Position.Y;
rotation = (float)Math.Atan2(Distance.Y, Distance.X); //calculates the rotation(trigonometry)
//angle = (float)(Math.Atan2(direction.Y, direction.X));
KeyboardState keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.A))
Position.X -= 2;
if (keyState.IsKeyDown(Keys.D))
Position.X += 2;
if (keyState.IsKeyDown(Keys.W))
Position.Y -= 2;
if (keyState.IsKeyDown(Keys.S))
Position.Y += 2;
//right and left edge detection
if (Position.X < 0)
Position = new Vector2(0, Position.Y);
int rightEdge = GraphicsDevice.Viewport.Width - player.Texture.Width;
if (Position.X > rightEdge)
Position = new Vector2(rightEdge, Position.Y);
//bottom and top edge detection
if (Position.Y < 0)
Position = new Vector2(Position.X, 0);
int bottomEdge = GraphicsDevice.Viewport.Height - player.Texture.Height;
if (Position.Y > bottomEdge)
Position = new Vector2(Position.X, bottomEdge);
if (!paused)
{
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
{
paused = true;
btnPlay.isClicked = false; //so that everytime its paused I can pause it again
}
enemy.Update();
}
else if(paused)
{
if (btnPlay.isClicked)
{
paused = false;
speed = 4;
}
if (btnExit.isClicked)
Exit();
btnPlay.Update(mouse);
btnExit.Update(mouse);
}
if (Keyboard.GetState().IsKeyDown(Keys.C))
{
spriteVelocity.X = (float)Math.Cos(rotation) * tangentialVelocity;
spriteVelocity.Y = (float)Math.Sin(rotation) * tangentialVelocity;
}
else if (spriteVelocity != Vector2.Zero)
{
float i = spriteVelocity.X;
float j = spriteVelocity.Y;
spriteVelocity.X = i -= friction * i;
spriteVelocity.Y = j -= friction * j;
}
if (Keyboard.GetState().IsKeyDown(Keys.Space) && pastKey.IsKeyUp(Keys.Space))
Fire();
pastKey = Keyboard.GetState();
UpdateBullets();
break;
case GameState.Exit:
this.Exit();
break;
}
base.Update(gameTime);
}
public void UpdateBullets()
{
foreach (Bullets bullet in bulletsList)
{
bullet.position += bullet.velocity;
if(Vector2.Distance(bullet.position, Position) > 500) //finds position
bullet.isVisible = false;
}
for (int i = 0; i < bulletsList.Count; i++)
{
if (!bulletsList[i].isVisible)
{
bulletsList.RemoveAt(i);
i--;
}
}
}
//function to handle movement of enemies
private void HandleMovingEnemy()
{
List<EnemySprite> toRemove = new List<EnemySprite>();
foreach (EnemySprite e in enemyList)
{
if (e.Position.X < (-20))
{
toRemove.Add(e);
}
else
e.Position -= new Vector2(speed, 0);
}
if (toRemove.Count > 0)
{
foreach (EnemySprite e in toRemove)
{
enemyList.Remove(e);
}
}
}
private void HandleCollision()//collision
{
Sprite toRemove = null;
if (bullet != null || enemyTexture != null)
{
foreach (EnemySprite e in enemyList) //checks each enemy sprite
{
if (bullet.BoundingBox.Intersects(enemy.BoundingBox)) //checks if a sprite has intersected an enemy
{
enemyList.Remove(enemy); //removes enemy
//toRemove = enemy;
break;
}
}
}
}
public void Fire()
{
Bullets newBullet = new Bullets(Content.Load<Texture2D>("graphics/bullet"));
Bullets.BulletTexture = Content.Load<Texture2D>("graphics/bullet");
//newBullet.LoadContent(LoadContent);
newBullet.velocity = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) * 5f + spriteVelocity;
newBullet.position = Position + newBullet.velocity * 5;
newBullet.isVisible = true;
if (bulletsList.Count() < 20)
bulletsList.Add(newBullet);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
switch (CurrentGameState)
{
case GameState.MainMenu:
spriteBatch.Draw(Content.Load<Texture2D>("Graphics/SeaSideDefenderMainMenu"), new Rectangle(0,0,screenWidth,screenHeight),Color.White);
btnPlay.Draw(spriteBatch);
btnExit.Draw(spriteBatch);
break;
case GameState.Playing:
spriteBatch.Draw(Content.Load<Texture2D>("Graphics/leveltest"), new Rectangle(0, 0, screenWidth, screenHeight), Color.White);
enemy = new EnemySprite();
enemy.Texture = Content.Load<Texture2D>("graphics/enemy");
enemy.Draw(spriteBatch);
spriteBatch.Draw(player.Texture, Position, null, Color.White, rotation, spriteOrigin, 1f, SpriteEffects.None, 0);
//player.Draw(spriteBatch);
foreach (EnemySprite e in enemyList)
{
e.Draw(spriteBatch);
}
foreach (Bullets bullet in bulletsList)
bullet.draw(spriteBatch);
/*for (int i; i < enemyList.Count; i++)
{
enemyList[i].Draw(spriteBatch);
}*/
if (paused)
{
speed = 0;
spriteBatch.Draw(Content.Load<Texture2D>("graphics/paused"), new Rectangle(0, 0, screenWidth, screenHeight), Color.White);
btnPlay.Draw(spriteBatch);
btnExit.Draw(spriteBatch);
}
break;
}
spriteBatch.End();
base.Draw(gameTime);
}
}
Bullets.cs
public class Bullets
{
public Texture2D texture;
public static Texture2D BulletTexture;
public Vector2 position;
public Vector2 velocity;
public Vector2 origin;
public bool isVisible;
public Rectangle BoundingBox
{
get { return new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height); }
}
public Bullets(Texture2D newTexture)
{
texture = newTexture;
isVisible = false;
}
public void draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture,position,null,Color.White,0f,origin,1f, SpriteEffects.None, 0);
}
public void LoadContent(ContentManager Content)
{
BulletTexture = Content.Load<Texture2D>(#"graphics/bullet");
}
}
enemy.cs
public class EnemySprite
{
public Texture2D Texture { get; set; }
public Vector2 Position {get; set; }
public Vector2 origin;
public Vector2 velocity;
public Rectangle rectangle;
float rotation = 0f;
bool right;
float distance;
float oldDistance;
public Rectangle BoundingBox
{
get { return new Rectangle((int)Position.X, (int)Position.Y, Texture.Width, Texture.Height); } //uses enemy position and wiwdth to create bounding box
}
public EnemySprite() { }
public EnemySprite(Texture2D texture, Vector2 position)
{
Texture = texture;
Position = position;
oldDistance = distance;
}
float mouseDistance;
public void Update()
{
Position += velocity;
origin = new Vector2(Texture.Width / 2, Texture.Height / 2);
if (distance <= 0)
{
right = true;
velocity.X = 1f;
}
else if(distance <= oldDistance)
{
right = false;
velocity.X = -1f;
}
if (right) distance += 1; else distance -= 1;
MouseState mouse = Mouse.GetState();
mouseDistance = mouse.X - Position.X;
if (mouseDistance >= -200 && mouseDistance <= 200)
{
if (mouseDistance < -1)
velocity.X = -1f;
else if (mouseDistance > 1)
velocity.X = 1f;
else if (mouseDistance == 0)
velocity.X = 0f;
}
}
public void Draw(SpriteBatch spriteBatch)
{
if (Texture != null)
spriteBatch.Draw(Texture, Position, Color.White);
if (velocity.X > 0)
{
spriteBatch.Draw(Texture, Position, null, Color.White, rotation, origin, 1f, SpriteEffects.FlipHorizontally, 0f);
}
else
{
spriteBatch.Draw(Texture, Position, null, Color.White, rotation, origin, 1f, SpriteEffects.None, 0f);
}
}
}
You've not initialized the global variable Bullet anywhere in your game1.cs, therefore you would never get bullet != null as true. Whereas, you'll always get enemyTexture != null as true since you've already initialized enemyTexture in the LoadContent().
Which means you'll always enter the if block while having the Bullet variable not initialized.
Hope this will lead you to the solution.
PS: Do mark the answer as 'Accepted' if this was the most helpful one.

Need some help implementing collisions in my game, with two separate classes

What I'm trying to do is to draw rectangles behind the background and make essentially collision detection. What I'm not sure however is how exactly I can implement that. I thought about making it so that as the sprite approached these rectangles, their speed would get slower and slower till they stop but would that work? Sorry if I sound a bit wet behind the ears, I'm fairly new to C# and am trying to self teach. Any help would be appreciated.
So I have a CharacterSprite class (walkingsprite) all the stuff about the frames is just a walking animation sequence I implemented.
namespace walkingsprite
{
class AnimatedSprite
{
//keyboard
KeyboardState currentKBState;
KeyboardState previousKBState;
Texture2D spriteTexture;
float timer = 0f;
float interval = 200f;
int currentFrame = 0;
int spriteWidth = 32;
int spriteHeight = 48;
int spriteSpeed = 2;
Rectangle sourceRect;
Texture2D obst;
Rectangle obst1;
Obstruction obstruction1;
Vector2 position;
Vector2 origin;
public Vector2 Position
{
get { return position; }
set { position = value; }
}
public Vector2 Origin
{
get { return origin; }
set { origin = value; }
}
public Texture2D Texture
{
get { return spriteTexture; }
set { spriteTexture = value; }
}
public Rectangle SourceRect
{
get { return sourceRect; }
set { sourceRect = value; }
}
public int SpriteSpeed
{
get { return spriteSpeed; }
set { spriteSpeed = value; }
}
public AnimatedSprite(Texture2D texture, int currentFrame, int spriteWidth, int spriteHeight)
{
this.spriteTexture = texture;
this.currentFrame = currentFrame;
this.spriteWidth = spriteWidth;
this.spriteHeight = spriteHeight;
}
public void HandleSpriteMovement(GameTime gameTime)
{
previousKBState = currentKBState;
currentKBState = Keyboard.GetState();
sourceRect = new Rectangle(currentFrame * spriteWidth, 0, spriteWidth, spriteHeight);
////////////////////////////////////////////////////////////////////
if (currentKBState.GetPressedKeys().Length == 0)
{
if (currentFrame > 0 && currentFrame < 4)
{
currentFrame = 0;
}
if (currentFrame > 4 && currentFrame < 8)
{
currentFrame = 4;
}
if (currentFrame > 8 && currentFrame < 12)
{
currentFrame = 8;
}
if (currentFrame > 12 && currentFrame < 16)
{
currentFrame = 12;
}
}
////////////////////////////////////////////////////////////////////
//sprintin
if (currentKBState.IsKeyDown(Keys.Space))
{
spriteSpeed = 2;
interval = 100;
}
else
{
spriteSpeed = 1;
interval = 200;
}
///////////////////////////////////////////////
if (currentKBState.IsKeyDown(Keys.Down) == true)
{
AnimateDown(gameTime);
if (position.Y < 575)
{
position.Y += spriteSpeed;
}
}
////////////////////////////////////////////////////
if (currentKBState.IsKeyDown(Keys.Up) == true)
{
AnimateUp(gameTime);
if (position.Y > 25)
{
position.Y -= spriteSpeed;
}
}
//////////////////////////////////////////////////////////
if (currentKBState.IsKeyDown(Keys.Right) == true)
{
AnimateRight(gameTime);
if (position.X < 780)
{
position.X += spriteSpeed;
}
}
////////////////////////////////////////////////////////////////////
if (currentKBState.IsKeyDown(Keys.Left) == true)
{
AnimateLeft(gameTime);
if (position.X > 0)
{
position.X -= spriteSpeed;
}
}
origin = new Vector2(sourceRect.Width / 2, sourceRect.Height / 2);
}
////////////////////////////////////////////////////////////////////
public void AnimateRight(GameTime gameTime)
{
if (currentKBState != previousKBState)
{
currentFrame = 9;
}
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if(timer > interval)
{
currentFrame++;
if(currentFrame > 11)
{
currentFrame = 8;
}
timer = 0f;
}
}
////////////////////////////////////////////////////////////////////
public void AnimateUp(GameTime gameTime)
{
if (currentKBState != previousKBState)
{
currentFrame = 13;
}
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if (timer > interval)
{
currentFrame++;
if (currentFrame > 15)
{
currentFrame = 12;
}
timer = 0f;
}
}
//////////////////////////////////////////
public void AnimateDown(GameTime gameTime)
{
if (currentKBState != previousKBState)
{
currentFrame = 1;
}
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if (timer > interval)
{
currentFrame++;
if (currentFrame > 3)
{
currentFrame = 0;
}
timer = 0f;
}
}
////////////////////////////////////////////////////
public void AnimateLeft(GameTime gameTime)
{
if (currentKBState != previousKBState)
{
currentFrame = 5;
}
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if (timer > interval)
{
currentFrame++;
if (currentFrame > 7)
{
currentFrame = 4;
}
timer = 0f;
}
}
}
}
And I have an obstruction class.
namespace walkingsprite
{
class Obstruction
{
Texture2D obst;
Rectangle obstRec1;
public Rectangle ObstRec1
{
get { return obstRec1; }
set { obstRec1 = value; }
}
public Texture2D Obst
{
get { return obst; }
set { obst = value; }
}
public Obstruction(Texture2D texture, Rectangle rec)
{
this.obstRec1 = rec;
this.obst = texture;
}
}
}
XNA already have a Rectangle class with a method to return if a rectangle collide with another rectangle.
An exemple:
Rectangle rec1 = new Rectangle(0, 0, 10, 10);
Rectangle rec2 = new Rectangle(5, 5, 10, 10);
rec1.Intersects(rec2); //Return true if a rectangle intersects another one
What people normally do, is a List of Rectangle and test one by one to know if they collide, or they implements a QuadTree but that is a bit more difficult in the beginning.
An exemple of a List of Rectangle:
List<Rectangle> allObjects = new List<Rectangle>();
Rectangle rec1 = new Rectangle(0, 0, 10, 10);
Rectangle rec2 = new Rectangle(10, 15, 10, 10);
Rectangle mainCharRec = new Rectangle(10, 20, 10, 10);
allObjects.Add(rec1);
allObjects.Add(rec2);
To test if main character rectangle intersects some other rectangles you can do a method with a foreach like this:
foreach (Rectangle rec in allObjects)
if(mainCharRec.Intersects(rec))
return true;
return false;
About getting slower, I think you could have a rectangle to the object and another to the "close region", and when the character enter in the region you slow his speed by the distance you give to the region, for example, if you have a rectangle with 10 pixels larger for each side, when character collides with larger rectangle he loses spriteSpeed/10 for step, until he stops. When the value is too much low, it turn 0:
if (spriteSpeed < 0.5)
spriteSpeed = 0;
else
spriteSpeed -= spriteSpeed/10;

How to create a texture at the players position and then leave it there XNA?

I have a game with an almost complete player class, but here's my issue. When I press control + K the player commits suicide (intended). Now, when he dies, it spawns a blood spatter at the players position (also intended) now here's the problem, once the player re spawns, the blood spatter DOES stay visible, but now it follows the player around, which is a little freaky if you ask me
So here is the main 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;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
namespace Teir_Tactical_2A
{
public class Player
{
Random random = new Random();
public Texture2D playerunarmed;
public Texture2D playerM1911;
public Texture2D bloodspatter2;
public Texture2D playerM4;
public KeyboardState keyState;
public SpriteFont Font1;
public KeyboardState oldKeyboardState;
public Vector2 playerPosition;
public SpriteBatch spriteBatch;
public float Angle { get; set; }
public float AngularVelocity { get; set; }
public Vector2 playerVelocity = Vector2.One;
public bool M1911;
public bool M4;
String[] strs = new String[] { "You suicided. Way to go Genius.", "I saw your limbs blow off with that one.", "Click to Respawn", "HAHAHAHAHAHA-Sorry Click to Respawn" };
String suicideStr;
public bool player;
public bool suicide;
public bool LMBpressed;
public bool RMBpressed;
public bool isplayeralive;
public bool isplayerdead;
public bool respawnscreen;
public bool bloodspatter;
float angle;
public Player(ContentManager content, Vector2 location)
{
this.playerunarmed = content.Load<Texture2D>("PLAYER");
this.playerM1911 = content.Load<Texture2D>("PLAYERM1911");
this.playerM4 = content.Load<Texture2D>("PLAYERM4");
this.bloodspatter2 = content.Load<Texture2D>("blood");
playerPosition = location;
suicideStr = strs[random.Next(strs.Length)];
M1911 = true;
M4 = true;
player = true;
LMBpressed = false;
suicide = false;
RMBpressed = false;
isplayeralive = true;
isplayerdead = false;
respawnscreen = false;
bloodspatter = false;
Font1 = content.Load<SpriteFont>("Font1");
}
public void Update()
{
MouseState curMouse = Mouse.GetState();
if (bloodspatter == true)
{
blood();
}
if (suicide == true)
{
suicided();
}
if (isplayeralive == true)
{
alive();
}
if (isplayerdead == true)
{
dead();
}
if (M1911 == true)
{
armedM1911();
}
if (M4 == true)
{
armedM4();
}
if (player == true)
{
unarmed();
}
if (LMBpressed == true)
{
LMBpressedA();
}
if (RMBpressed == true)
{
RMBpressedA();
}
Vector2 mouseLoc = new Vector2(curMouse.X, curMouse.Y);
Vector2 direction = mouseLoc - playerPosition;
angle = (float)(Math.Atan2(direction.Y, direction.X));
if (curMouse.LeftButton == ButtonState.Pressed)
{
LMBpressed = true;
}
if (curMouse.RightButton == ButtonState.Pressed)
{
RMBpressed = true;
}
keyState = Keyboard.GetState();
if (isplayeralive == false && LMBpressed == true)
{
isplayeralive = true;
isplayerdead = false;
suicide = false;
suicideStr = strs[random.Next(strs.Length)];
}
if (keyState.IsKeyDown(Keys.LeftControl) && keyState.IsKeyDown(Keys.K))
{
isplayeralive = false;
isplayerdead = true;
bloodspatter = true;
suicide = true;
}
if (keyState.IsKeyDown(Keys.D1))
{
M1911 = false;
M4 = false;
player = true;
}
if (keyState.IsKeyDown(Keys.D2))
{
M1911 = true;
player = false;
}
if (keyState.IsKeyDown(Keys.D3))
{
M4 = true;
M1911 = false;
player = false;
}
if (keyState.IsKeyDown(Keys.D))
playerPosition.X += playerVelocity.X + 1;
if (keyState.IsKeyDown(Keys.A))
playerPosition.X -= playerVelocity.X + 1;
if (keyState.IsKeyDown(Keys.W))
playerPosition.Y -= playerVelocity.Y + 1;
if (keyState.IsKeyDown(Keys.S))
playerPosition.Y += playerVelocity.Y + 1;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Begin();
{
Rectangle sourceRectangle = new Rectangle(0, 0, playerunarmed.Width, playerunarmed.Height);
Vector2 origin = new Vector2(playerunarmed.Width / 2, playerunarmed.Height / 2);
if (M1911 == true)
{
spriteBatch.Draw(playerM1911, new Rectangle((int)playerPosition.X, (int)playerPosition.Y, playerunarmed.Width, playerunarmed.Height), null, Color.White, angle + 90, new Vector2(86, 88), SpriteEffects.None, 0f);
}
if (suicide == true)
{
spriteBatch.DrawString(Font1, suicideStr, new Vector2(10, 670), Color.Red);
}
}
if (bloodspatter == true)
{
spriteBatch.Draw(bloodspatter2, new Rectangle((int)playerPosition.X, (int)playerPosition.Y, bloodspatter2.Width, bloodspatter2.Height), Color.White);
}
if (player == true)
{
spriteBatch.Draw(playerunarmed, new Rectangle((int)playerPosition.X, (int)playerPosition.Y, playerunarmed.Width, playerunarmed.Height), null, Color.White, angle + 90, new Vector2(86, 88), SpriteEffects.None, 0f);
}
if (M4 == true)
{
spriteBatch.Draw(playerM4, new Rectangle((int)playerPosition.X, (int)playerPosition.Y, playerunarmed.Width, playerunarmed.Height), null, Color.White, angle + 90, new Vector2(86, 88), SpriteEffects.None, 0f);
}
if (LMBpressed == true)
{
spriteBatch.DrawString(Font1, "LMB PRESSED (shot taken prototype)", new Vector2(1000, 22), Color.GreenYellow);
}
if (RMBpressed == true)
{
spriteBatch.DrawString(Font1, "RMB PRESSED (grenade thrown prototype)", new Vector2(968, 34), Color.Red);
}
if (RMBpressed == true && LMBpressed == true)
{
spriteBatch.DrawString(Font1, "If you are seeing this, the mouse is functioning correctly", new Vector2(810, 45), Color.Black);
}
spriteBatch.End();
}
public void armedM1911()
{
M1911 = true;
M4 = false;
player = false;
}
public void armedM4()
{
M4 = true;
M1911 = false;
player = false;
}
public void unarmed()
{
M1911 = false;
M4 = false;
}
public void LMBpressedA()
{
LMBpressed = false;
}
public void RMBpressedA()
{
RMBpressed = false;
}
public void alive()
{
M1911 = false;
player = true;
M4 = false;
respawnscreen = false;
}
public void dead()
{
M1911 = false;
player = false;
M4 = false;
respawnscreen = true;
}
public void blood()
{
bloodspatter = true;
}
public void suicided()
{
suicide = true;
}
}
}
Here is where I THINK the problem is (95% sure) I need to get the players coordinates and set them as the location for the bloodspatter (and spawn more if necessary).
if (bloodspatter == true)
{
spriteBatch.Draw(bloodspatter2, new Rectangle((int)playerPosition.X, (int)playerPosition.Y, bloodspatter2.Width, bloodspatter2.Height), Color.White);
}
Its probably because of the way I used the playerPosition as the X/Y coordinates, but I don't know how to tell it to get them first and then set the bloodspatters location to where the player suicided.
EDIT: It appears that theres a misunderstanding, I Don't want the blood texture to disappear, I want it to Stay where the player last died (in this case, suiciding, until I can add bullets which call it) Basically, performance is not a problem as its a very low res texture, and in addition I only want them to disappear if the game is closing or the level is changing (not an issue here)
If you want a single blood spot to remain after suicide, you could use add a single Vector2 to your Player class and name it like PlaceOfDeath. Default it to a new Vector2.Zero(); When you die, set the location of your hero to be the new PlaceOfDeath and then use that Vector2 as the drawing point for your sprite.
If you want to draw EVERY place your player has died, you could create a List of Vector2s (List) and call it PlacesOfDeath. Default it to an empty list. When you die, set the location of your hero with a PlacesOfDeath.Add({Vector2 Location of Hero}).
Then in your draw code you could iterate over each Vector2 in the PlacesOfDeath list and draw the blood spatter on each place.
So now to the code
For single blood placement -
Add to your class properties / members declarations:
private Vector2 placeOfDeath = new Vector2.Zero();
Add to your suicide method,
placeOfDeath = playerPosition;
Change your if(bloodsplatter == true) conditional codeblock in the Draw method:
spriteBatch.Draw(bloodspatter2, new Rectangle((int)placeOfDeath.X, (int)placeOfDeath.Y, bloodspatter2.Width, bloodspatter2.Height), Color.White);
For multiple blood spots
Add to your class properties / members declarations:
private List placesOfDeath = new List();
Add to your suicide method,
placesOfDeath.Add(playerPosition);
Change your if(bloodsplatter == true) conditional codeblock in the Draw method:
foreach(Vector2 placeOfDeath in placesOfDeath){
spriteBatch.Draw(bloodspatter2, new Rectangle((int)placeOfDeath.X, (int)placeOfDeath.Y, bloodspatter2.Width, bloodspatter2.Height), Color.White);
}
do not connect player with bloodsplater. make it independed. so when player die just call function that will create blood at current player position.
create a list where you will store all bloodsplatter, and then just add new bloodsplatter into that list. and then in gamplay class call draw and update for this list.
pseudo:
splater (position as vector)
splaterlist inherit list of splater
- sub add new splater(position)
- sub update each splater, add duration, fade out
- sub draw each splater
player class
if player die add new splater into splaterlist
gameplay class
update player, draw player
update splaterlist, drawsplaterlist

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