Jumping animation - c#

stayI need to make an animation while my sprite is jumping. I tried to load an animation if a key is pressed but it doesn't function. I jump by pressing Space key. All others animations function. So, my problem is to load an animation by pressing a key. I think I could use GameTime.Elapsed.TotalMilliseconds but I am not sure. I am new anyway and it is my first game.
class Player
{
PlayerAnimation animation;
Animation walk;
Animation stay;
Animation jump;;
public Vector2 position;
public Vector2 velocity;
public Rectangle rect;
public bool jumping = false;
public int health = 5;
public Vector2 Position{ get { return position; } }
public Player() { }
public void Load(ContentManager Content) {
walk = new Animation(Content.Load<Texture2D>("walk"), 46, 0.1f, true, rect);
animazioneMinima = new Animation(Content.Load<Texture2D>("stay"),37, 0.15f, true, rect);
jump = new Animation(Content.Load<Texture2D>("jump"), 51, 0.1f, true , rect);
}
public void Update(GameTime gameTime)
{
position += velocity;
rect = new Rectangle((int)position.X, (int)position.Y, 43, 46);
Input(gameTime);
if (velocity.X != 0)
PlayerAnimation.PlayAnimation(walk);
else if (velocity.X == 0)
PlayerAnimation.PlayAnimation(stay;
if (velocity.Y < 10)
velocity.Y += 0.4f;
}
private void Input(GameTime gameTime)
{
if (Keyboard.GetState().IsKeyDown(Keys.D))
velocity.X = (float)gameTime.ElapsedGameTime.TotalMilliseconds / 3;
else if (Keyboard.GetState().IsKeyDown(Keys.A))
velocity.X = -(float)gameTime.ElapsedGameTime.TotalMilliseconds / 3;
else velocity.X = 0f;
if (Keyboard.GetState().IsKeyDown(Keys.Space) && jumping == false)
{
position.Y -= 5f;
velocity.Y = -9f;
jumping = true;
}
}
public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
SpriteEffects rotate = SpriteEffects.None;
if (velocity.X >= 0)
rotate = SpriteEffects.None;
else if (velocity.X < 0)
rotate = SpriteEffects.FlipHorizontally;
PlayerAnimation.Draw(gameTime, spriteBatch, position, rotate);
}
}
}
what should i make? :D

I don't know exactly how your code works, but maybe yau can write something like:
if (velocity.Y != 0)
{
PlayerAnimation.PlayAnimation(jump);
velocity.Y -= 0.05f
}
and insted of:
if (Keyboard.GetState().IsKeyDown(Keys.Space) && jumping == false)`
you can write:
if (Keyboard.GetState().IsKeyDown(Keys.Space) && velocity.Y == 0)
then you can skip using the jump bool completely.

Related

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

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.

Enemies shoot all the time

I want that an enemy shoots a bullet if the variable nextShot is bigger than the variable shotFrequency. Each enemy should fire independently.
But for the moment, every enemy is shooting all the time. Their are no breaks between the shots. But I want that their always is a little break between the shots. I'm sure that something is wrong about the Enemy class, but I don't know what to change. Could somebody help me, please?
public class Map
{
Texture2D myEnemy, myBullet;
Player Player;
List<Enemy> enemieslist = new List<Enemy>();
List<Bullet> bulletslist = new List<Bullet>();
float fNextEnemy = 0.0f;
float fEnemyFreq = 2.0f;
Vector2 Startposition = new Vector2(200, 200);
Vector2 CurrentEnemyPosition;
GraphicsDeviceManager graphicsDevice;
public Map(GraphicsDeviceManager device)
{
graphicsDevice = device;
}
public void Load(ContentManager content)
{
myEnemy = content.Load<Texture2D>("enemy");
myBullet = content.Load<Texture2D>("bullet");
Player = new Player(graphicsDevice);
Player.Load(content);
}
public void Update(GameTime gameTime)
{
Player.Update(gameTime);
float delta = (float)gameTime.ElapsedGameTime.TotalSeconds;
for(int i = enemieslist.Count - 1; i >= 0; i--)
{
// Update Enemy
Enemy enemy = enemieslist[i];
enemy.Update(gameTime, this.graphicsDevice, Player.playershape.Position, delta);
CurrentEnemyPosition = enemy.Bulletstartposition;
// Does the enemy shot?
if (enemy.Shot == true)
// New bullet
{
Vector2 bulletDirection = Vector2.Normalize(Player.playershape.Position - CurrentEnemyPosition) * 200f;
bulletslist.Add(new Bullet(CurrentEnemyPosition, bulletDirection, Player.playershape.Position));
}
}
this.fNextEnemy += delta;
//New enemy
if (this.fNextEnemy >= fEnemyFreq)
{
Vector2 enemyDirection = Vector2.Normalize(Player.playershape.Position - Startposition) * 100f;
enemieslist.Add(new Enemy(Startposition, enemyDirection, Player.playershape.Position));
fNextEnemy = 0;
}
for(int i = bulletslist.Count - 1; i >= 0; i--)
{
// Update Bullet
Bullet bullets = bulletslist[i];
bullets.Update(gameTime, this.graphicsDevice, delta);
}
}
public void Draw(SpriteBatch batch)
{
Player.Draw(batch);
foreach (Enemy enemies in enemieslist)
{
enemies.Draw(batch, myEnemy);
}
foreach (Bullet bullets in bulletslist)
{
bullets.Draw(batch, myBullet);
}
}
}
Enemy class:
public class Enemy
{
private float nextShot = 0;
private float shotFrequency = 1.0f;
Vector2 vPos;
Vector2 vMove;
Vector2 vPlayer;
public Vector2 Bulletstartposition;
public bool Remove;
public bool Shot;
public Enemy(Vector2 Pos, Vector2 Move, Vector2 Player)
{
this.vPos = Pos;
this.vMove = Move;
this.vPlayer = Player;
this.Remove = false;
this.Shot = false;
}
public void Update(GameTime gameTime, GraphicsDeviceManager graphics, Vector2 PlayerPos, float delta)
{
nextShot += delta;
if (nextShot >= shotFrequency)
{
this.Shot = true;
nextShot = 0;
}
if (!Remove)
{
float fMoveTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
this.vMove = Vector2.Normalize(PlayerPos - this.vPos) * 100f;
this.vPos += this.vMove * fMoveTime;
Bulletstartposition = this.vPos;
if (this.vPos.X > graphics.PreferredBackBufferWidth + 1)
{
this.Remove = true;
}
else if (this.vPos.X < -20)
{
this.Remove = true;
}
if (this.vPos.Y > graphics.PreferredBackBufferHeight + 1)
{
this.Remove = true;
}
else if (this.vPos.Y < -20)
{
this.Remove = true;
}
}
}
public void Draw(SpriteBatch spriteBatch, Texture2D myTexture)
{
if (!Remove)
{
spriteBatch.Draw(myTexture, this.vPos, Color.White);
}
}
}
Bullet class
public class Bullet
{
Vector2 vPos;
Vector2 vMove;
Vector2 vPlayer;
public bool Remove;
public Bullet(Vector2 Pos, Vector2 Move, Vector2 Player)
{
this.Remove = false;
this.vPos = Pos;
this.vMove = Move;
this.vPlayer = Player;
}
public void Update(GameTime gameTime, GraphicsDeviceManager graphics, float delta)
{
if (!Remove)
{
float fMoveTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
this.vPos.X += this.vMove.X * fMoveTime;
this.vPos.Y += this.vMove.Y * fMoveTime;
if (this.vPos.X > graphics.PreferredBackBufferWidth +1)
{
this.Remove = true;
}
else if (this.vPos.X < -20)
{
this.Remove = true;
}
if (this.vPos.Y > graphics.PreferredBackBufferHeight +1)
{
this.Remove = true;
}
else if (this.vPos.Y < -20)
{
this.Remove = true;
}
}
}
public void Draw(SpriteBatch spriteBatch, Texture2D myTexture)
{
if (!Remove)
{
spriteBatch.Draw(myTexture, this.vPos, Color.White);
}
}
}
You are never clearing the Shot flag. After you have an enemy shoot, just do enemy.Shot = false;.
Also, a tiny tip, when nextShot is >= shotFrequency, it's better to do this:
nextShot -= shotFrequency;
It accounts for the tiny bit of overlap when you go beyond shotFrequency.

XNA 3.1 Movement Collision Issue

So heres my problem. I have a box that I want my character to move around. But I want to be able to move around it while holding multiple move commands, for instance..
when moving right (towards the left of the obstacle) I want to be able to hold move right and up or down at the same time without the character sticking to the box. The funny part is, it works fine for the left and right side of the obstacle, yet it sticks when i try it on the top and bottom side of the obstacle.
Heres the Player Class (object im moving)
<!-- language: c# -->
public class Player
{
public Texture2D texture;
public Vector2 position;
public int speed;
public Vector2 offset;
public bool left, right, up, down;
public Rectangle collisionRect
{
get
{
return new Rectangle((int)position.X , (int)position.Y, texture.Width, texture.Height);
}
}
public Vector2 direction;
public Player(Texture2D texture, Vector2 position, int speed)
{
this.texture = texture;
this.position = position;
this.speed = speed;
offset.X = speed;
offset.Y = speed;
left = false;
right = false;
up = false;
down = false;
}
public virtual void Update(GameTime gameTime, Rectangle clientBounds)
{
direction = Vector2.Zero;
if (Keyboard.GetState().IsKeyDown(Keys.A))
{
direction.X -= 1;
left = true;
}
else
left = false;
if (Keyboard.GetState().IsKeyDown(Keys.D))
{
direction.X += 1;
right = true;
}
else
right = false;
if (Keyboard.GetState().IsKeyDown(Keys.W))
{
direction.Y -= 1;
up = true;
}
else
up = false;
if (Keyboard.GetState().IsKeyDown(Keys.S))
{
direction.Y += 1;
down = true;
}
else
down = false;
position += (direction * speed);
}
public virtual void Draw(GameTime gameTime, SpriteBatch spritebatch)
{
spritebatch.Draw(texture, collisionRect, Color.White);
}
}
Heres the Update Method in my maingame
<!-- language: c# -->
public override void Update(GameTime gameTime)
{
// TODO: Add your update code here
player.Update(gameTime, Game.Window.ClientBounds);
if (player.right && HitWall(player))
{
player.position.X -= player.offset.X;
}
else if (player.left && HitWall(player))
{
player.position.X += player.offset.X;
}
if (player.down && HitWall(player))
{
player.position.Y -= player.offset.Y;
}
else if (player.up && HitWall(player))
{
player.position.Y += player.offset.Y;
}
base.Update(gameTime);
}
And the HitWall function
<!-- language: c# -->
public bool HitWall(Player player)
{
for (int i = player.collisionRect.Top; i < player.collisionRect.Bottom; i++)
for (int j = player.collisionRect.Left; j < player.collisionRect.Right; j++)
if (TextureData[i * gameMap.map.Width + j] != Color.White)
return true;
return false;
}
I'm not sure where offset is defined, but I'm assuming it's the movement you've just made that frame.
Your problem is that because you check left & right before up and down, if you're moving diagonally down onto the top edge of the box, then you'll register a hit in the Y direction — HitWall doesn't check which direction you're going, it just checks for a collision. Therefore, the collision in the Y axis stil counts on the line if (player.right && HitWall(player)) and stops your lateral movement.
Best bet is to apply your sideways movement, check for a hit, move back if there is one — then apply your downwards movement, check for a hit, and move back if there is one. Correcting the position like this should mean you slide along the sides as you want.

Categories