Severe Movement Lag - C#, XNA - c#

I'm very new to programming C#, and well, programming anything. This is my third 2D game, I've encountered a problem. For some reason, the game gets laggy extremely fast when I'm attempting to move my sprite, and I can't figure out why.
Here's the Sheep class:
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace IdeaLess
{
class Sheep
{
//-//-//-//-//-//
public Texture2D SheepTexture;
public const float SheepSpeed = 0.5f;
public Vector2 SheepPosition;
public int Width
{
get { return SheepTexture.Width; }
}
public int Height
{
get { return SheepTexture.Height; }
}
//-//-//-//-//-//
public void Initialize(Texture2D texture, Vector2 position)
{
SheepTexture = texture;
SheepPosition = position;
}
public void Update()
{
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(SheepTexture, SheepPosition, null, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 0f);
}
}
}
And the Game1.cs:
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 IdeaLess
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
//CLASS OBJECTS
Sheep sheep;
Pig pig;
//SHEEP
float SheepMoveSpeed;
//PIG
float PigMoveSpeed;
//KEYBOARDSTATES
KeyboardState currentKeyboardState;
KeyboardState previousKeyboardState;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
sheep = new Sheep();
pig = new Pig();
SheepMoveSpeed = 5f;
PigMoveSpeed = 4f;
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
Vector2 sheepPosition = new Vector2(20, 30);
Vector2 pigPosition = new Vector2(20, 400);
sheep.Initialize(Content.Load<Texture2D>("Sheep"), sheepPosition);
pig.Initialize(Content.Load<Texture2D>("Pig"), pigPosition);
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
previousKeyboardState = currentKeyboardState;
currentKeyboardState = Keyboard.GetState();
UpdateSheep(gameTime);
UpdatePig(gameTime);
base.Update(gameTime);
}
private void UpdateSheep(GameTime gameTime)
{
if (currentKeyboardState.IsKeyDown(Keys.Left))
sheep.SheepPosition.X -= SheepMoveSpeed;
if (currentKeyboardState.IsKeyDown(Keys.Right))
sheep.SheepPosition.X += SheepMoveSpeed;
}
private void UpdatePig(GameTime gameTime)
{
if (currentKeyboardState.IsKeyDown(Keys.A))
pig.PigPosition.X -= PigMoveSpeed;
if (currentKeyboardState.IsKeyDown(Keys.D))
pig.PigPosition.X += PigMoveSpeed;
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
spriteBatch.Begin();
sheep.Draw(spriteBatch);
pig.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
So far the game is made up of nothing but a player class (Sheep) and the Game1.cs. There is also a pig class; identical to the sheep one.
Basically, whenever I hold 'Right Arrow', the sprite moves jerky and unevenly, sometimes slowing down to almost stationary, and sometimes it moves normally for a moment before lagging again.
It's not just the sprite movement, but it's the FPS. I know this because I've encountered this lag on a previous game and it caused the background music to stop and the timer from ticking.
Any ideas what might be causing this?

Well good news, it looks like it is nothing major! A thing I always encourage new XNA programmers to do, is add Elapsed time! Basicly, depending on how fast your system is running at a given time, may effect how fast your sprite moves depending on how many frames per seconds you have. If you tried this on a different computer it may run at a completely different speed.
To correct this you need to modify your UpdateAnimal() Methods
private void UpdateSheep(GameTime gameTime)
{
//How much time has passed since the last frame, incase we lag and skip a frame, or take too long, we can process accordingly
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
if (currentKeyboardState.IsKeyDown(Keys.Left))
sheep.SheepPosition.X -= SheepMoveSpeed * elapsed; // Multiply by elapsed!
if (currentKeyboardState.IsKeyDown(Keys.Right))
sheep.SheepPosition.X += SheepMoveSpeed * elapsed;
}
Now, depending on your computer specs, elapsed will be a very small fraction of 1 (second) so you will need to increase your SheepMoveSpeed until your sprite starts moving.
If this dosen't work, you can try using a profiler to see what is causing lag, or add an fps timer to see if it is really "laggy" or just a matter of not moving properly.
I would also encourage you to create an Animal class, and create other classes that inherit from it.

Related

How to move my sprite in MonoGame using C#

First off, i'm fairly new to programming, about 2 months in, i dabbled a bit in Console Application, WinForms, and still using the ugly console to get better at algorithms in general. But now, I wanna start digging into game programming, because that's the reason i wanted to learn programming. I stumbled upon MonoGame, and while it's harder than say Unity, I got an immense sense of achievement after creating something by just using code. I already made a Space Invaders and Pong but nothing related to sprite animation, using spritesheets and moving a player. So 2 days ago, I started a platformer, divided my spritesheet, got some animation down, and now that it's time to move my player, I'm completely lost. I tried reading some tutorials on vectors, but it doesn't help in my case. Maybe you can shed some light on the matter.
So, without further ado, here's the code:
Game.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace MafiaJohnny
{
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
private JohnnyPlayer johnnyPlayer;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
Texture2D texture = Content.Load<Texture2D>("JohnnyDone");
johnnyPlayer = new JohnnyPlayer(texture, 2, 4);
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
johnnyPlayer.Update(gameTime);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
johnnyPlayer.Draw(spriteBatch, new Vector2(200, 200));
base.Draw(gameTime);
}
}
}
JohnnyPlayer.cs
using System;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;
namespace MafiaJohnny
{
class JohnnyPlayer
{
public Texture2D Texture { get; set; }
public int Rows { get; set; }
public int Columns { get; set; }
private int currentFrame;
private int totalFrames;
//Slow down frame animation
private int timeSinceLastFrame = 0;
private int millisecondsPerFrame = 400;
public JohnnyPlayer(Texture2D texture, int rows, int columns)
{
Texture = texture;
Rows = rows;
Columns = columns;
currentFrame = 0;
totalFrames = Rows * Columns;
}
public void Update (GameTime gameTime)
{
timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
if (timeSinceLastFrame > millisecondsPerFrame)
{
timeSinceLastFrame -= millisecondsPerFrame;
KeyboardState keystate = Keyboard.GetState();
//Idle animation
if (keystate.GetPressedKeys().Length == 0)
currentFrame++;
timeSinceLastFrame = 0;
if (currentFrame == 2)
currentFrame = 0;
//Walking Animation
if (keystate.IsKeyDown(Keys.Left))
{
}
}
}
public void Draw (SpriteBatch spriteBatch, Vector2 location)
{
int width = Texture.Width/Columns;
int height = Texture.Height / Rows;
int row = (int) ((float) currentFrame/Columns);
int column = currentFrame % Columns;
Rectangle sourceRectangle = new Rectangle(width * column, height * row, width, height);
Rectangle destinationRectangle = new Rectangle((int)location.X, (int)location.Y, width, height);
spriteBatch.Begin();
spriteBatch.Draw(Texture, destinationRectangle, sourceRectangle, Color.White);
spriteBatch.End();
}
}
}
So here's my code, find me an answer minions! Thank you is what I mean :)
You just need to change "location" so the sprite moves left/right/up/down. Also I recommend moving this code from JohnnyPlayer to another "controller" class.
Here:
http://www.gamefromscratch.com/post/2015/06/15/MonoGame-Tutorial-Creating-an-Application.aspx
They make a sprite and move it from left to right. In your case the texture on sprite changes in time (animation) but the movement is still the same.

XNA Sprite doesn't seem to be updating?

I've looked through some other questions and haven't found my answer so I'm asking you lovely people as you have helped me before :)
I have a main class (RPG.cs) and a player class (Player.cs) and I want the Player class to be as self-contained as possible (because I don't want a huuuge main class) but here is my problem.
Problem
My Player sprite draws fine but when I want it to move, it won't update! At the moment I'm attempting to make it act like a cursor to test movement but eventually I'll have it bound to WASD or the arrow keys. So I want my sprite to follow my mouse at the moment but it just stays at 50, 50 (it's preset starting position) Have I missed something obvious? I'm new to XNA and I've spent half an hour on this problem!
RPG.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 TestGame
{
public class RPG : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D PlayerTex;
Rectangle playerPos = new Rectangle(
Convert.ToInt32(Player.Pos.X),
Convert.ToInt32(Player.Pos.Y), 32, 32);
public RPG()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
}
protected override void Initialize() { base.Initialize(); }
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
PlayerTex = Content.Load<Texture2D>("testChar");
}
protected override void UnloadContent() { }
protected override void Update(GameTime gameTime)
{
if
(
GamePad.GetState(PlayerIndex.One)
.Buttons.Back == ButtonState.Pressed
)
this.Exit();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
spriteBatch.Begin();
spriteBatch.Draw(PlayerTex, playerPos, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
Player.cs
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 TestGame
{
/// This is a game component that implements IUpdateable.
public class Player : Microsoft.Xna.Framework.GameComponent
{
public static Vector2 Pos = new Vector2(50, 50);
MouseState ms = Mouse.GetState();
public Player(Game game) : base(game) { }
/// Allows the game component to perform
/// any initialization it needs to before
/// starting to run. This is where it can
/// query for any required services and load content.
public override void Initialize() { base.Initialize(); }
/// Allows the game component to update itself.
public override void Update(GameTime gameTime)
{
Pos.X = ms.X;
Pos.Y = ms.Y;
base.Update(gameTime);
}
}
}
Hope you can help! :)
As mentioned in the comment, I am not going to solve every problem. But the main errors.
Let the player be responsible for its position, not the game. Furthermore, I would make the player responsible for drawing itself, but that goes a bit too far for this answer.
The following code should at least work.
public class Player : Microsoft.Xna.Framework.GameComponent
{
public Vector2 Pos { get; set; }
public Player(Game game) : base(game)
{
this.Pos = new Vector2(50, 50);
}
public override void Initialize() { base.Initialize(); }
public override void Update(GameTime gameTime)
{
var ms = Mouse.GetState();
Pos.X = ms.X;
Pos.Y = ms.Y;
base.Update(gameTime);
}
}
Then use the player in your game:
public class RPG : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D PlayerTex;
Player player;
public RPG()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
player = new Player(this);
Components.Add(player);
}
protected override void Initialize() { base.Initialize(); }
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
PlayerTex = Content.Load<Texture2D>("testChar");
}
protected override void UnloadContent() { }
protected override void Update(GameTime gameTime)
{
if
(
GamePad.GetState(PlayerIndex.One)
.Buttons.Back == ButtonState.Pressed
)
this.Exit();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.White);
spriteBatch.Begin();
spriteBatch.Draw(PlayerTex, player.Pos, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
I have removed the texture's size. Don't know if you really need this. If so, you can let Player expose a Rectangle, not just a Vector2.
The key solution which Nico included is just that you using the original rectangle coordinates you made when you draw:
Rectangle playerPos = new Rectangle(
Convert.ToInt32(Player.Pos.X),
Convert.ToInt32(Player.Pos.Y), 32, 32);
Here you make the rectangle using the players CURRENT starting time position.
Then you ALWAYS draw based on this rectangle you made ages ago and never updated:
spriteBatch.Draw(PlayerTex, playerPos, Color.White);
The right way as Nico mentioned is just to change the draw to this:
playerPos = new Rectangle(
Convert.ToInt32(Player.Pos.X),
Convert.ToInt32(Player.Pos.Y), 32, 32);
spriteBatch.Draw(PlayerTex, playerPos, Color.White);
Now you will be drawing at a new place every time. There are better ways to do this (like what nico did) but here is the core idea.

xna model not appearing, advice needed

What I have:
game class
model class for my ship
Camera class
when I Press F5 my game opens, it shows blue, but my model doesnt appear, anyone got any advice for why this is happening?
if anyone would be able to help i would really thankful.
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 test1
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
//Visual components
Ship ship = new Ship();
Camera _camera;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
this.graphics.ToggleFullScreen();
this._camera = new Camera(graphics.GraphicsDevice.Viewport);
this._camera.LookAt = new Vector3(0.0f, 0.0f, -1.0f);
base.Initialize();
}
protected override void LoadContent()
{
ship.Model = Content.Load<Model>("Models/p1_wedge");
ship.Transforms = _camera.SetupEffectDefaults(ship.Model);
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed ||
Keyboard.GetState().IsKeyDown(Keys.Escape))
this.Exit();
// Get some input.
UpdateInput();
base.Update(gameTime);
}
protected void UpdateInput()
{
// Get the game pad state.
GamePadState currentState = GamePad.GetState(PlayerIndex.One);
KeyboardState currentKeyState = Keyboard.GetState();
ship.Update(currentState);
}
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
//camera
this._camera.Update();
_camera.LookAt = ship.Position;
Matrix shipTransformMatrix = ship.RotationMatrix
* Matrix.CreateTranslation(ship.Position);
DrawModel(ship.Model, shipTransformMatrix, ship.Transforms);
base.Draw(gameTime);
}
public static void DrawModel(Model model, Matrix modelTransform,
Matrix[] absoluteBoneTransforms)
{
//Draw the model, a model can have multiple meshes, so loop
foreach (ModelMesh mesh in model.Meshes)
{
//This is where the mesh orientation is set
foreach (BasicEffect effect in mesh.Effects)
{
effect.World =
absoluteBoneTransforms[mesh.ParentBone.Index] *
modelTransform;
}
mesh.Draw();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace test1
{
class Ship
{
public Model Model;
public Matrix[] Transforms;
//Position of the model in world space
public Vector3 Position = Vector3.Zero;
//Velocity of the model, applied each frame to the model's position
public Vector3 Velocity = Vector3.Zero;
private const float VelocityScale = 5.0f;
public Matrix RotationMatrix =
Matrix.CreateRotationX(MathHelper.PiOver2);
private float rotation;
public float Rotation
{
get { return rotation; }
set
{
float newVal = value;
while (newVal >= MathHelper.TwoPi)
{
newVal -= MathHelper.TwoPi;
}
while (newVal < 0)
{
newVal += MathHelper.TwoPi;
}
if (rotation != value)
{
rotation = value;
RotationMatrix =
Matrix.CreateRotationX(MathHelper.PiOver2) *
Matrix.CreateRotationZ(rotation);
}
}
}
public void Update(GamePadState controllerState)
{
KeyboardState currentKeyState = Keyboard.GetState();
if (currentKeyState.IsKeyDown(Keys.A))
Rotation += 0.10f;
else
// Rotate the model using the left thumbstick, and scale it down.
Rotation -= controllerState.ThumbSticks.Left.X * 0.10f;
if (currentKeyState.IsKeyDown(Keys.D))
Rotation -= 0.10f;
if (currentKeyState.IsKeyDown(Keys.W))
Velocity += RotationMatrix.Forward * VelocityScale;
else
// Finally, add this vector to our velocity.
Velocity += RotationMatrix.Forward * VelocityScale *
controllerState.Triggers.Right;
// In case you get lost, press A to warp back to the center.
if (currentKeyState.IsKeyDown(Keys.Enter))
{
Position = Vector3.Zero;
Velocity = Vector3.Zero;
Rotation = 0.0f;
}
Position += Velocity;
Velocity *= 0.95f;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Graphics;
namespace test1
{
public class Camera
{
private Vector3 _position;
private Vector3 _lookAt;
private Matrix _viewMatrix;
private Matrix _projectionMatrix;
private float _aspectRatio;
public Camera(Viewport viewport)
{
this._aspectRatio = ((float)viewport.Width) / ((float)viewport.Height);
this._projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
MathHelper.ToRadians(40.0f),
this._aspectRatio,
20000.0f,
30000.0f);
}
public Vector3 Position
{
get { return this._position; }
set { this._position = value; }
}
public Vector3 LookAt
{
get { return this._lookAt; }
set { this._lookAt = value; }
}
public Matrix ViewMatrix
{
get { return this._viewMatrix; }
}
public Matrix ProjectionMatrix
{
get { return this._projectionMatrix; }
}
public void Update()
{
this._viewMatrix =
Matrix.CreateLookAt(this._position, this._lookAt, Vector3.Up);
}
public Matrix[] SetupEffectDefaults(Model myModel)
{
Matrix[] absoluteTransforms = new Matrix[myModel.Bones.Count];
myModel.CopyAbsoluteBoneTransformsTo(absoluteTransforms);
foreach (ModelMesh mesh in myModel.Meshes)
{
foreach (BasicEffect effect in mesh.Effects)
{
effect.EnableDefaultLighting();
effect.Projection = ProjectionMatrix;
effect.View = ViewMatrix;
}
}
return absoluteTransforms;
}
}
}
EDIT
public static void DrawModel(Model model, Matrix modelTransform,
Matrix[] absoluteBoneTransforms)
{
//Draw the model, a model can have multiple meshes, so loop
foreach (ModelMesh mesh in model.Meshes)
{
//This is where the mesh orientation is set
foreach (BasicEffect effect in mesh.Effects)
{
effect.World =
absoluteBoneTransforms[mesh.ParentBone.Index] *
modelTransform;
effect.Projection = _camera.ProjectionMatrix;
effect.View = _camera.ViewMatrix;
}
//Draw the mesh, will use the effects set above.
mesh.Draw();
}
I think there are 2 issues with your code:
Look At You don't seem to update the Look At of your camera to point towards your spaceship, either make your camera "track" the spaceship by giving it a reference to it and in your Update update the look at position or manually update the lookat position from your Game1.
View / Projection Matrix Even though your camera has a view matrix and a projection matrix, you don't use them in your DrawModel. When you assign your world, consider adding the two following lines
effect.Projection = _camera.ProjectionMatrix;
effect.View = _camera.ViewMatrix;
There are possibly several issues in your code preventing it from working as expected. The two that pop out at me is that 1.) you never set the camera position so it defaults to 0,0,0 which colocates it with the ship model. So your camera is actually inside the model and any triangle that is in it's view would be culled as a backside triangle if 2.) it wasn't already frustrum culled since your nearplane is set to 20000.

XNA Respawning "enemies" randomly

I am trying to make a game and I want "enemies" or meteors to spawn from the right side and going to the left side. I am working on some code and it seems to be working pretty good but the respawning fails. They end up spawning one and one REALLY slow and then after a while they don't spawn at all. All help would be really appreciated.
Here's 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 WindowsGame2
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
List<Enemies> enemies = new List<Enemies>();
Random random = new Random();
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
}
protected override void UnloadContent()
{
}
float spawn = 0;
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
spawn += (float)gameTime.ElapsedGameTime.TotalSeconds;
foreach (Enemies enemy in enemies)
{
enemy.Update(graphics.GraphicsDevice);
}
LoadEnemies();
base.Update(gameTime);
}
public void LoadEnemies()
{
int randY = random.Next(100, 400);
if (spawn > 1)
{
spawn = 0;
if (enemies.Count() < 10)
enemies.Add(new Enemies(Content.Load<Texture2D>("meteor"), new Vector2(1110, randY)));
}
for (int i = 0; i < enemies.Count; i++)
{
if (!enemies[i].isVisible)
{
enemies.RemoveAt(i);
i--;
}
}
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
foreach (Enemies enemy in enemies)
{
enemy.Draw(spriteBatch);
}
spriteBatch.End();
base.Draw(gameTime);
}
}
}
and here's my class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace WindowsGame2
{
class Enemies
{
public Texture2D texture;
public Vector2 position;
public Vector2 velocity;
public bool isVisible = true;
Random random = new Random();
int randX, randY;
public Enemies(Texture2D newTexture, Vector2 newPosition)
{
texture = newTexture;
position = newPosition;
randX = random.Next(-4, 4);
randY = random.Next(-4, -1);
velocity = new Vector2(randX, randY);
}
public void Update(GraphicsDevice graphics)
{
position += velocity;
if (position.Y <= 0 || position.Y >= graphics.Viewport.Height - texture.Height)
{
velocity.Y = -velocity.Y;
}
if (position.X < 0 - texture.Width)
{
isVisible = false;
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, position, Color.White);
}
}
}
Your problem lies here. Some of your meteors are moving right and some are not moving at all.
randX = random.Next(-4, 4);
Try using
randX = random.Next(-4, -1);
Your enemies/meteors sometimes had a velocity on the X that was between 0 and 4, so they moved right.
I can see you changed the Y to this, maybe you got them mixed up?

'particleEngine' being drawn against a vector

I'm using XNA and C#.
I have a problem with calling a vector variable from my particleEmitter. I can draw the particle just fine if it is static or not moving. And when I have a vector variable that is set to a fixed position of (x,y) it's okay and draws on the screen. But if I have a vector variable that has been set to move in the x or y axis it does not draw at all.
Declared variables:
Vector2 shipPos;
float shipMovement;
ParticleEngine particleEngine;
And a method that loads stuff about what should happen with the vectors and the way it should behave:
public void loadEmitter(GameTime gameTime)
{
shipMovement = 2f;
shipPos.Y -= shipMovement;
particleEngine.EmitterLocation = new Vector2(shipPos.X,shipPos.Y);
}
I'm trying to get particleEngine to trail the movement of a ship. What I can't seem to do is get it to draw when I set this up to happen.
Other info: ParticleEngine is a class in itself and basically sets some parameters about how the particles I will be drawing should behave. I have other screens with the spritebatch Begin and End calls. Other than that, here's the code for my main class:
namespace PlanetDrill2
{
class LaunchScreen : Screen
{
Texture2D LaunchScreenTexture;
Texture2D shipLaunch;
Vector2 shipPos;
float shipMovement;
ParticleEngine particleEngine;
Vector2 smokePos;
public LaunchScreen(Game game, SpriteBatch batch, ChangeScreen changeScreen)
: base(game, batch, changeScreen)
{
}
protected override void SetupInputs()
{
base.SetupInputs();
}
public override void Activate()
{
base.Activate();
}
public void LaunchShip()
{
}
public void loadEmitter(GameTime gameTime)
{
shipMovement = 2f;
shipPos.Y -= shipMovement;
particleEngine.EmitterLocation = new Vector2(shipPos.X,shipPos.Y);
}
protected override void LoadScreenContent(ContentManager content)
{
LaunchScreenTexture = content.Load<Texture2D>("launchTest");
shipLaunch = content.Load<Texture2D>("shipLaunch");
List<Texture2D> textures = new List<Texture2D>();
textures.Add(content.Load<Texture2D>("smoketexture"));
particleEngine = new ParticleEngine(textures, new Vector2(0, 0));
base.LoadScreenContent(content);
}
protected override void UpdateScreen(GameTime gameTime, DisplayOrientation screenOrientation)
{
//if (gameTime.TotalGameTime.Seconds>10)
//{
// changeScreenDelegate(ScreenState.UMA);
//}
loadEmitter(gameTime);
particleEngine.Update();
base.UpdateScreen(gameTime, screenOrientation);
}
protected override void DrawScreen(SpriteBatch batch, DisplayOrientation screenOrientation)
{
batch.Draw(LaunchScreenTexture, Vector2.Zero, Color.White);
batch.Draw(shipLaunch, new Vector2(80, 450) +shipPos, Color.White);
particleEngine.Draw(batch);
base.DrawScreen(batch, screenOrientation);
}
protected override void SaveScreenState()
{
base.SaveScreenState();
}
} // end class LaunchScreen
} // end namespace PlanetDrill2
From here
batch.Draw(shipLaunch, new Vector2(80, 450) +shipPos, Color.White);
particleEngine.Draw(batch);
It looks like you are drawing the ship relative to [80, 450], but you are not applying this offset to the particleEngine.

Categories