I was just messing around with XNA and trying to get a simple player class that could move around through keyboard controls. I can't seem to get it to draw the way I have it set up now though. I'm not seeing what error I'm making.
Here's the Actor base class:
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace RunnerTEst
{
class Actor
{
public static List<Actor> actors;
public Texture2D texture;
protected Vector2 position;
protected float rotation;
protected float scale;
protected Color color;
#region Constructors
static Actor()
{
actors = new List<Actor>();
}
public Actor(Texture2D texture)
{
actors.Add(this);
this.texture = texture;
this.position = Vector2.Zero;
this.rotation = 0f;
this.scale = 1f;
}
#endregion
#region Properties
public Vector2 Position
{
get { return this.position; }
set { this.position = value; }
}
public Vector2 Origin
{
get { return new Vector2(this.position.X + this.texture.Width / 2,
this.position.Y + this.texture.Height / 2); }
}
public float Rotation
{
get { return this.rotation; }
set { this.rotation = value; }
}
public float Scale
{
get { return this.scale; }
set { this.scale = value; }
}
public Color Color
{
get { return this.color; }
set { this.color = value; }
}
public float Width
{
get { return this.texture.Width; }
}
public float Height
{
get { return this.texture.Height; }
}
#endregion
#region Methods
public virtual void Update(GameTime gameTime)
{
}
public virtual void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(this.texture, this.position, this.color);
}
#endregion
}
}
Player class:
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace RunnerTEst
{
class Player : Actor
{
private const float speed = 5f;
protected Vector2 velocity;
private static KeyboardState currState, prevState;
static Player()
{
currState = prevState = Keyboard.GetState();
}
public Player(Texture2D texture, Vector2 position)
: base(texture)
{
this.position = position;
this.velocity = Vector2.Zero;
}
public override void Update(GameTime gameTime)
{
this.HandleInput();
this.position += this.velocity;
foreach (Actor actor in Actor.actors)
{
if (this == actor)
continue;
this.CheckCollision(actor);
}
base.Update(gameTime);
}
public override void Draw(SpriteBatch spriteBatch)
{
base.Draw(spriteBatch);
}
public void CheckCollision(Actor actor)
{
//--left/right sides
if (this.position.X + this.Width > actor.Position.X) //right of this hitting left actor
{
this.position.X = actor.Position.X - this.Width;
}
else if (this.position.X < (actor.Position.X + actor.Width))//left this hit right actor
{
this.position.X = actor.Position.X + actor.Width;
}
//--top/bottom
if (this.position.Y + this.Height > actor.Position.Y) //this bottom hit actor top
{
this.position.Y = actor.Position.Y - this.Width;
}
else if (this.position.Y < (actor.Position.Y + actor.Height))//this top hit actor bottom
{
this.position.Y = actor.Position.Y + actor.Height;
}
//TODO: check screen bounds
}
public void HandleInput()
{
currState = Keyboard.GetState();
if (currState.IsKeyDown(Keys.W))
{
this.velocity.Y = -speed;
}
else if (currState.IsKeyDown(Keys.S))
{
this.velocity.Y = speed;
}
else
{
this.velocity.Y = 0f;
}
if (currState.IsKeyDown(Keys.A))
{
this.velocity.X = -speed;
}
else if (currState.IsKeyDown(Keys.D))
{
this.velocity.X = speed;
}
else
{
this.velocity.X = 0f;
}
prevState = currState;
}
}
}
and lastly, the game:
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 RunnerTEst
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D playerTexture;
Player me;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
playerTexture = Content.Load<Texture2D>(#"Textures\player");
me = new Player(playerTexture, new Vector2(200, 200));
}
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)
this.Exit();
me.Update(gameTime);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
me.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
Thanks in advance for your time!
I looked through it, and it looks like you never define the Actor's color property. This means that the color variable defaults to black, which means that the tint given to the Draw line (spriteBatch.Draw(this.texture, this.position, this.color);) is Black, which hides the sprite.
Just set the color of the Actor to white somewhere (I just set it underneath me = new Player(playerTexture, new Vector2(200, 200));).
So the new LoadContent would look like:
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
playerTexture = Content.Load<Texture2D>(#"Textures\player");
me = new Player(playerTexture, new Vector2(200, 200));
me.Color = Color.White;
}
Hope that helps,
max
Related
Im making a spaceinvaderisch kinda game in XNA/Monogame
Everything was going great until I encountered this problem.
Ive been trying to fix the bullet hitboxes for days but to no succes.
My problem lies in the fact that the hitbox doesnt move with the bullet itself.
The Collision detection is in the Game1 class. The actual movement in Bullets class and the trigger to shoot is in the Tank class. The Bullet is also inherited to Sprite.cs which gives it a hitbox.
Could anyone help me out. I really just want to finish what ive started before I start working on something else.
Help is Dearly Appreciated.
Game1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace IsisInvaders
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Tank Tank;
Isis Isis1;
Isis Isis2;
Isis Isis3;
Isis Isis4;
Isis Isis5;
Isis Isis6;
Isis Isis7;
Isis Isis8;
Isis Isis9;
Isis Isis10;
Isis Isis11;
Bullets Bullets;
private Song BgMusic;
int screenWidth;
int screenHeight;
enum GameState
{
MainMenu,
Playing,
}
GameState CurrentGameState = GameState.MainMenu;
Button btnPlay;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
//Bullet = new Bullets(Tank.position);
Tank = new Tank(new Vector2 (375,425));
Isis1 = new Isis(new Vector2(30, 0));
Isis2 = new Isis(new Vector2(70, 0));
Isis3 = new Isis(new Vector2(110, 0));
Isis4 = new Isis(new Vector2(150, 0));
Isis5 = new Isis(new Vector2(190, 0));
Isis6 = new Isis(new Vector2(230, 0));
Isis7 = new Isis(new Vector2(270, 0));
Isis8 = new Isis(new Vector2(310, 0));
Isis9 = new Isis(new Vector2(350, 0));
Isis10 = new Isis(new Vector2(390, 0));
Isis11 = new Isis(new Vector2(430, 0));
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
graphics.PreferredBackBufferHeight = 800;
graphics.PreferredBackBufferHeight = 600;
graphics.ApplyChanges();
btnPlay = new Button(Content.Load<Texture2D>("Start"), graphics.GraphicsDevice);
IsMouseVisible = true;
spriteBatch = new SpriteBatch(GraphicsDevice);
btnPlay.setPosition(new Vector2(350, 300));
BgMusic = Content.Load<Song>("Music");
Tank.LoadContent(this.Content, "Tank");
Isis1.LoadContent(this.Content, "Isis");
Isis2.LoadContent(this.Content, "Isis");
Isis3.LoadContent(this.Content, "Isis");
Isis4.LoadContent(this.Content, "Isis");
Isis5.LoadContent(this.Content, "Isis");
Isis6.LoadContent(this.Content, "Isis");
Isis7.LoadContent(this.Content, "Isis");
Isis8.LoadContent(this.Content, "Isis");
Isis9.LoadContent(this.Content, "Isis");
Isis10.LoadContent(this.Content, "Isis");
Isis11.LoadContent(this.Content, "Isis");
Sounds.BgMusic(BgMusic);
screenWidth = GraphicsDevice.Viewport.Width;
screenHeight = GraphicsDevice.Viewport.Height;
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
// TODO: Add your update logic here
//Bullet.Update(screenWidth, screenHeight, gameTime);
MouseState mouse = Mouse.GetState();
switch (CurrentGameState)
{
case GameState.MainMenu:
if (btnPlay.isClicked == true)
{
CurrentGameState = GameState.Playing;
}
btnPlay.Update(mouse);
break;
case GameState.Playing:
Isis1.Update(screenWidth, screenHeight, gameTime);
Isis2.Update(screenWidth, screenHeight, gameTime);
Isis3.Update(screenWidth, screenHeight, gameTime);
Isis4.Update(screenWidth, screenHeight, gameTime);
Isis5.Update(screenWidth, screenHeight, gameTime);
Isis6.Update(screenWidth, screenHeight, gameTime);
Isis7.Update(screenWidth, screenHeight, gameTime);
Isis8.Update(screenWidth, screenHeight, gameTime);
Isis9.Update(screenWidth, screenHeight, gameTime);
Isis10.Update(screenWidth, screenHeight, gameTime);
Isis11.Update(screenWidth, screenHeight, gameTime);
Tank.Update(screenWidth, screenHeight, gameTime);
break;
}
//Collision
foreach (Bullets item in Tank.bullets)
{
if (item.Bullethitbox.Intersects(Isis1.Box))
{
Isis1.LoadContent(this.Content, "DeadIsis");
}
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.SandyBrown);
spriteBatch.Begin();
switch (CurrentGameState)
{
case GameState.MainMenu:
spriteBatch.Draw(Content.Load<Texture2D>("MainMenu"), new Rectangle(0, 0, 800, 600), Color.White);
btnPlay.Draw(spriteBatch);
break;
case GameState.Playing:
Tank.Draw(spriteBatch);
Isis1.Draw(spriteBatch);
Isis2.Draw(spriteBatch);
Isis3.Draw(spriteBatch);
Isis4.Draw(spriteBatch);
Isis5.Draw(spriteBatch);
Isis6.Draw(spriteBatch);
Isis7.Draw(spriteBatch);
Isis8.Draw(spriteBatch);
Isis9.Draw(spriteBatch);
Isis10.Draw(spriteBatch);
Isis11.Draw(spriteBatch);
break;
}
//Bullet.Draw(spriteBatch);
spriteBatch.End();
// TODO: Add your drawing code here
base.Draw(gameTime);
}
}
}
Bullets.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace IsisInvaders
{
class Bullets : Sprite
{
private Vector2 Position;
public Bullets(Vector2 Position) : base(Position)
{
this.Position = Position;
}
public override void Update(int screenWidth, int Screenheight, GameTime gametime)
{
int Pos = (int)Position.Y;
Pos -= 10;
Position.Y = Pos;
}
public override void LoadContent(ContentManager Contentman, string Spritename)
{
base.LoadContent(Contentman, Spritename);
spritetext = Contentman.Load<Texture2D>("Bullet");
//this.Box = new Rectangle((int)Position.X, (int)Position.Y, spritetext.Width, spritetext.Height);
}
public override void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(spritetext, Position, Color.White);
}
public Texture2D Bulletsprite { get { return this.spritetext; } }
public Vector2 Bulletposition { get { return this.Position; } set { this.Position = value; } }
public Rectangle Bullethitbox { get { return this.Box; } set { this.Box = value; } }
}
}
Tank.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace IsisInvaders
{
class Tank : Sprite
{
private Vector2 P;
private KeyboardState KBS = Keyboard.GetState();
private float bulletspeed = -400f;
public List<Bullets> bullets = new List<Bullets>();
private float reload = 0;
Bullets Bullet;
ContentManager Content;
public Tank(Vector2 Position) : base(Position)
{
}
public override void Update(int screenWidth, int Screenheight, GameTime gametime)
{
KBS = Keyboard.GetState();
P = this.position;
if (KBS.IsKeyDown(Keys.Right))
{
P.X += 8;
this.position = P;
}
if (KBS.IsKeyDown(Keys.Left))
{
P.X -= 8;
this.position = P;
}
reload += (float)gametime.ElapsedGameTime.TotalMilliseconds;
if (reload >= 500 && KBS.IsKeyDown(Keys.Space))
{
Bullets b = new Bullets(position);
b.LoadContent(Content, "Bullet");
bullets.Add(b);
reload = 0;
}
foreach (Bullets item in bullets)
{
//item.Bullethitbox = new Rectangle((int)item.Bulletposition.X, (int)item.Bulletposition.Y, item.Bulletsprite.Width, item.Bulletsprite.Height);
item.Update(screenWidth, Screenheight, gametime);
}
//for (int i = 0; i < bullets.Count; i++)
//{
// float y = bullets[i].position.Y;
// y += bulletspeed * (float)gametime.ElapsedGameTime.TotalSeconds;
// bullets[i] = new Bullets(new Vector2(bullets[i].position.X, y));
//}
}
public override void LoadContent(ContentManager Contentman, string Spritename)
{
base.LoadContent(Contentman, Spritename);
this.Content = Contentman;
}
public override void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(spritetext, position, Color.White);
foreach (Bullets b in bullets)
{
b.Draw(spriteBatch);
}
//for (int i = 0; i < bullets.Count; i++)
//{
// spriteBatch.Draw(Bullet.Bulletsprite, position, Color.White);
//}
}
}
}
Isis.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace IsisInvaders
{
class Isis : Sprite
{
private Vector2 P;
public Isis(Vector2 Position) : base (Position)
{
P = Position;
}
public override void Update(int screenWidth, int screenHeight, GameTime gametime)
{
//P.Y += (float)0.11;
this.position = P;
this.Box = new Rectangle((int)P.X, (int)P.Y, spritetext.Width, spritetext.Height);
}
}
}
Sprite.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace IsisInvaders
{
class Sprite
{
private Texture2D SpriteTexture;
private Rectangle Hitbox;
private Vector2 Position;
public Sprite(Vector2 Position)
{
this.Position = Position;
}
public virtual void Update(int screenWidth, int Screenheight, GameTime gametime)
{
}
public virtual void LoadContent(ContentManager Contentman, string Spritename)
{
SpriteTexture = (Contentman.Load<Texture2D>(Spritename));
}
public virtual void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(SpriteTexture, Position, Color.White);
}
public Texture2D spritetext { get { return this.SpriteTexture; } set { this.SpriteTexture = value; } }
public Vector2 position { get { return this.Position; } set { this.Position = value; } }
public Rectangle Box { get { return new Rectangle((int)Position.X, (int)Position.Y, SpriteTexture.Width, SpriteTexture.Height); } set { this.Hitbox = value; } }
}
}
In your Bullets class you got a local variable called Position which will be modified in Bullets.Update(GameTime) but your hitbox refers to the Position vector in your Sprite class. Hope it helps.
when i start to debug my code it loads fine but only the fade in happens when i press Z the Enter key does not cause the fade or the next menu with text "Title Screen"to appear i wonder if anyone could tell me where i went wrong ill upload the full code below.
p.s. there is no error message.
what should happen when the game starts "Splash screen"
should appear on the screen pressing enter fades out the screen to the Title screen saying "Title Screen", the splash screen loads and when Z is pressed the fade animation happens but the Enter key has 0 effect on the game.
namespace Platformer
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
Screen_Manager.Instance.Initiaize();
Screen_Manager.Instance.Dimensions = new Vector2(800, 600);
graphics.PreferredBackBufferWidth = (int)Screen_Manager.Instance.Dimensions.X;
graphics.PreferredBackBufferHeight = (int)Screen_Manager.Instance.Dimensions.Y;
graphics.ApplyChanges();
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
Screen_Manager.Instance.LoadContent(Content);
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
Screen_Manager.Instance.Update(gameTime);
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
Screen_Manager.Instance.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
{
public class Game_Screen
{
protected ContentManager content;
public virtual void LoadContent(ContentManager Content)
{
content = new ContentManager(Content.ServiceProvider, "content");
}
public virtual void UnloadContent()
{
content.Unload();
}
public virtual void Update(GameTime gameTime)
{
}
public virtual void Draw(SpriteBatch spriteBatch)
{
}
}
}
{
public class Screen_Manager
{
#region variables
ContentManager content; // creating custom ContentManger
Game_Screen currentScreen; // screen being currently displayed
Game_Screen newScreen; // new screen taking effect
private static Screen_Manager instance; // Screen Manger instance
// Dictionary<string, Game_Screen> screens = new Dictionary<string, Game_Screen>(); // Game Screen storage
Stack<Game_Screen> screenStack = new Stack<Game_Screen>(); // screens Stack
Vector2 dimensions; // width&Height of Screens
bool transition;
Fade_Animation fade;
Texture2D fadeTexture;
#endregion
#region Properties
public static Screen_Manager Instance
{
get
{
if (instance == null)
instance = new Screen_Manager();
return instance;
}
}
public Vector2 Dimensions
{
get { return dimensions; }
set { dimensions = value; }
}
#endregion
#region Main Methods
public void AddScreen(Game_Screen screen)
{
transition = true;
newScreen = screen;
fade.IsActive = true;
fade.Alpha = 1.0f;
fade.ActivateValue = 1.0f;
}
public void Initiaize()
{
currentScreen = new Splash_Screen();
fade = new Fade_Animation();
}
public void LoadContent(ContentManager Content)
{
content = new ContentManager(Content.ServiceProvider, "Content");
currentScreen.LoadContent(Content);
fadeTexture = content.Load<Texture2D>("fade");
fade.LoadContent(content, fadeTexture, "", Vector2.Zero);
fade.Scale = dimensions.X;
}
public virtual void Update(GameTime gameTime)
{
if (!transition)
currentScreen.Update(gameTime);
else
Transition(gameTime);
}
public virtual void Draw(SpriteBatch spriteBatch)
{
currentScreen.Draw(spriteBatch);
if (transition)
fade.Draw(spriteBatch);
}
#endregion
#region Provate Methods
private void Transition(GameTime gameTime)
{
fade.Update(gameTime);
if(fade.Alpha == 1.0f && fade.Timer.TotalSeconds == 1.0f)
{
screenStack.Push(newScreen);
currentScreen.UnloadContent();
currentScreen = newScreen;
currentScreen.LoadContent(content);
}
else if (fade.Alpha == 0.0f)
{
transition =false;
fade.IsActive = false;
}
}
#endregion
}
}
{
public class Splash_Screen : Game_Screen
{
KeyboardState keystate;
SpriteFont font;
public override void LoadContent(ContentManager Content)
{
base.LoadContent(Content);
if (font == null)
font = content.Load<SpriteFont>("Font1");
}
public override void UnloadContent()
{
base.UnloadContent();
}
public override void Update(GameTime gameTime)
{
keystate = Keyboard.GetState();
if (keystate.IsKeyDown(Keys.Z))
Screen_Manager.Instance.AddScreen(new Title_Screen());
}
public override void Draw(SpriteBatch spriteBatch)
{
spriteBatch.DrawString(font, "SplashScreen",
new Vector2(100, 100), Color.Black);
}
}
}
{
public class Title_Screen : Game_Screen
{
KeyboardState keystate;
SpriteFont font;
public override void LoadContent(ContentManager Content)
{
base.LoadContent(Content);
if (font == null)
font = content.Load<SpriteFont>("Font1");
}
public override void UnloadContent()
{
base.UnloadContent();
}
public override void Update(GameTime gameTime)
{
keystate = Keyboard.GetState();
if (keystate.IsKeyDown(Keys.Enter))
Screen_Manager.Instance.AddScreen(new Splash_Screen());
}
public override void Draw(SpriteBatch spriteBatch)
{
spriteBatch.DrawString(font, "Title Screen",
new Vector2(100, 100), Color.Black);
}
}
}
{
public class Animation
{
protected Texture2D image;
protected string text;
protected SpriteFont font;
protected Color color;
protected Rectangle sourceRect;
protected float rotation, scale, axis, alpha;
protected Vector2 origin, position;
protected ContentManager content;
protected bool isActive;
public virtual float Alpha
{
get { return alpha; }
set { alpha = value; }
}
public bool IsActive
{
set { isActive = value; }
get { return isActive; }
}
public float Scale
{
set { scale = value; }
// get { return scale; }
}
public virtual void LoadContent(ContentManager Content, Texture2D image,
string text, Vector2 position)
{
content = new ContentManager(Content.ServiceProvider, "Content");
this.image = image;
this.text = text;
this.position = position;
if (text != string.Empty)
{
font = Content.Load<SpriteFont>("Font1");
color = new Color(114, 77, 225);
}
if (image != null)
sourceRect = new Rectangle(0, 0, image.Width, image.Height);
rotation = 0.0f;
axis = 0.0f;
scale = 1.0f;
alpha = 1.0f;
isActive = false;
}
public virtual void UnloadContent()
{
content.Unload();
text = string.Empty;
position = Vector2.Zero;
sourceRect = Rectangle.Empty;
image = null;
}
public virtual void Update(GameTime gameTime)
{
}
public virtual void Draw(SpriteBatch spriteBatch)
{
if (image != null)
{
origin = new Vector2(sourceRect.Width / 2,
sourceRect.Height / 2);
spriteBatch.Draw(image, position + origin, sourceRect,
Color.White * alpha, rotation, origin, scale,
SpriteEffects.None, 0.0f);
}
if (text != String.Empty)
{
origin = new Vector2(font.MeasureString(text).X / 2,
font.MeasureString(text).Y / 2);
spriteBatch.DrawString(font, text, position + origin,
color * alpha, rotation, origin, scale, SpriteEffects.None,
0.0f);
}
}
}
}
{
class Fade_Animation : Animation
{
bool increase;
float fadespeed;
TimeSpan defaultTime, timer;
bool startTimer;
float activatevalue;
bool stopUpdateing;
float defaultAlpha;
public TimeSpan Timer
{
get { return timer; }
set { defaultTime = value; timer = defaultTime; }
}
public float FadeSpeed
{
get { return fadespeed; }
set { fadespeed = value; }
}
public override float Alpha
{
get
{
return alpha;
}
set
{
alpha = value;
if (alpha == 1.0f)
increase = false;
else if (alpha == 0.0f)
increase = true;
}
}
public float ActivateValue
{
get { return activatevalue; }
set { activatevalue = value; }
}
public override void LoadContent(ContentManager Content,
Texture2D image, string text, Vector2 position)
{
base.LoadContent(Content, image, text, position);
increase = false;
fadespeed = 1.0f;
defaultTime = new TimeSpan(0, 0, 1);
timer = defaultTime;
activatevalue = 0.0f;
stopUpdateing = false;
defaultAlpha = alpha;
}
public override void Update(GameTime gameTime)
{
if (isActive)
{
if (!stopUpdateing)
{
if (!increase)
alpha -= fadespeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
else
alpha += fadespeed * (float)gameTime.ElapsedGameTime.TotalSeconds;
if (alpha <= 0.0f)
alpha = 0.0f;
else if (alpha >= 1.0f)
alpha = 1.0f;
}
if (alpha == activatevalue)
{
stopUpdateing = true;
timer -= gameTime.ElapsedGameTime;
if (timer.TotalSeconds <= 0)
{
increase = !increase;
timer = defaultTime;
stopUpdateing = false;
}
}
}
else
{
alpha = defaultAlpha;
}
}
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am right now trying to display a vector holding an X and Y value, for a sprite, from one class Game Object.cs to Game1.cs. I move a protected value (protected Vector2 velocity;) to a public Vector2 velocity when I move it over the draw method (so that it will show how fast the sprite on screen is moving) it comes up with Error 1 An object reference is required for the non-static field, method, or property. So I add static, now it's public static Vector2 velocitys, and play the game. When I look at the X and Y value, they'er there but will not change when I move. I have had this problem on anything with a static.
Is there a way to get rid of the static, or fix this so I can see the X and Y update while I am playing? I have the velocitys Vector take velocity's X and Y in the update in GameObject.cs so that it will constantly take from velocity.
Why does it need a static? Can I change that? Can I update it on the screen?
This is the code:
GameObject.cs:
(Holdes the Vectors velocitys and velocity)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Tile_Engine;
namespace **
{
public class GameObject
{
#region Declarations
protected Vector2 worldLocation;
protected Vector2 velocity;
protected int frameWidth;
protected int frameHeight;
protected bool enabled;
protected bool flipped = false;
protected bool onGround;
protected Rectangle collisionRectangle;
protected int collideWidth;
protected int collideHeight;
protected bool codeBasedBlocks = true;
protected float drawDepth = 0.85f;
protected Dictionary<string, AnimationStrip> animations =
new Dictionary<string, AnimationStrip>();
protected string currentAnimation;
public Vector2 velocitys;
#endregion
#region Properties
public bool Enabled
{
get { return enabled; }
set { enabled = value; }
}
public Vector2 WorldLocation
{
get { return worldLocation; }
set { worldLocation = value; }
}
public Vector2 WorldCenter
{
get
{
return new Vector2(
(int)worldLocation.X + (int)(frameWidth / 2),
(int)worldLocation.Y + (int)(frameHeight / 2));
}
}
public Rectangle WorldRectangle
{
get
{
return new Rectangle(
(int)worldLocation.X,
(int)worldLocation.Y,
frameWidth,
frameHeight);
}
}
public Rectangle CollisionRectangle
{
get
{
return new Rectangle(
(int)worldLocation.X + collisionRectangle.X,
(int)worldLocation.Y + collisionRectangle.Y,
collisionRectangle.Width,
collisionRectangle.Height);
}
set { collisionRectangle = value; }
}
#endregion
#region Helper Methods
private void updateAnimation(GameTime gameTime)
{
if (animations.ContainsKey(currentAnimation))
{
if (animations[currentAnimation].FinishedPlaying)
{
PlayAnimation(animations[currentAnimation].NextAnimation);
}
else
{
animations[currentAnimation].Update(gameTime);
}
}
}
#endregion
#region Public Methods
public void PlayAnimation(string name)
{
if (!(name == null) && animations.ContainsKey(name))
{
currentAnimation = name;
animations[name].Play();
}
}
public virtual void Update(GameTime gameTime)
{
if (!enabled)
return;
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
updateAnimation(gameTime);
if (velocity.Y != 0)
{
velocitys = velocity;
onGround = false;
}
Vector2 moveAmount = velocity * elapsed;
moveAmount = horizontalCollisionTest(moveAmount);
moveAmount = verticalCollisionTest(moveAmount);
Vector2 newPosition = worldLocation + moveAmount;
newPosition = new Vector2(
MathHelper.Clamp(newPosition.X, 0,
Camera.WorldRectangle.Width - frameWidth),
MathHelper.Clamp(newPosition.Y, 2 * (-TileMap.TileHeight),
Camera.WorldRectangle.Height - frameHeight));
worldLocation = newPosition;
}
public virtual void Draw(SpriteBatch spriteBatch)
{
if (!enabled)
return;
if (animations.ContainsKey(currentAnimation))
{
SpriteEffects effect = SpriteEffects.None;
if (flipped)
{
effect = SpriteEffects.FlipHorizontally;
}
spriteBatch.Draw(
animations[currentAnimation].Texture,
Camera.WorldToScreen(WorldRectangle),
animations[currentAnimation].FrameRectangle,
Color.White, 0.0f, Vector2.Zero, effect, drawDepth);
}
}
#endregion
#region Map-Based Collision Detecting Methods
private Vector2 horizontalCollisionTest(Vector2 moveAmount)
{
if (moveAmount.X == 0)
return moveAmount;
Rectangle afterMoveRect = CollisionRectangle;
afterMoveRect.Offset((int)moveAmount.X, 0);
Vector2 corner1, corner2;
if (moveAmount.X < 0)
{
corner1 = new Vector2(afterMoveRect.Left,
afterMoveRect.Top + 1);
corner2 = new Vector2(afterMoveRect.Left,
afterMoveRect.Bottom - 1);
}
else
{
corner1 = new Vector2(afterMoveRect.Right,
afterMoveRect.Top + 1);
corner2 = new Vector2(afterMoveRect.Right,
afterMoveRect.Bottom - 1);
}
Vector2 mapCell1 = TileMap.GetCellByPixel(corner1);
Vector2 mapCell2 = TileMap.GetCellByPixel(corner2);
if (!TileMap.CellIsPassable(mapCell1) ||
!TileMap.CellIsPassable(mapCell2))
{
moveAmount.X = 0;
velocity.X = 0;
}
if (codeBasedBlocks)
{
if (TileMap.CellCodeValue(mapCell1) == "BLOCK" ||
TileMap.CellCodeValue(mapCell2) == "BLOCK")
{
moveAmount.X = 0;
velocity.X = 0;
}
}
return moveAmount;
}
private Vector2 verticalCollisionTest(Vector2 moveAmount)
{
if (moveAmount.Y == 0)
return moveAmount;
Rectangle afterMoveRect = CollisionRectangle;
afterMoveRect.Offset((int)moveAmount.X, (int)moveAmount.Y);
Vector2 corner1, corner2;
if (moveAmount.Y < 0)
{
corner1 = new Vector2(afterMoveRect.Left + 1,
afterMoveRect.Top);
corner2 = new Vector2(afterMoveRect.Right - 1,
afterMoveRect.Top);
}
else
{
corner1 = new Vector2(afterMoveRect.Left + 1,
afterMoveRect.Bottom);
corner2 = new Vector2(afterMoveRect.Right - 1,
afterMoveRect.Bottom);
}
Vector2 mapCell1 = TileMap.GetCellByPixel(corner1);
Vector2 mapCell2 = TileMap.GetCellByPixel(corner2);
if (!TileMap.CellIsPassable(mapCell1) ||
!TileMap.CellIsPassable(mapCell2))
{
if (moveAmount.Y > 0)
onGround = true;
moveAmount.Y = 0;
velocity.Y = 0;
}
if (codeBasedBlocks)
{
if (TileMap.CellCodeValue(mapCell1) == "BLOCK" ||
TileMap.CellCodeValue(mapCell2) == "BLOCK")
{
if (moveAmount.Y > 0)
onGround = true;
moveAmount.Y = 0;
velocity.Y = 0;
}
}
return moveAmount;
}
#endregion
}
}
Game1.cs:
(Draws the Vector2 velocity)
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 Tile_Engine;
namespace **
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Player player;
SpriteFont pericles8;
Vector2 scorePosition = new Vector2(20, 580);
enum GameState { TitleScreen, Playing, PlayerDead, GameOver };
GameState gameState = GameState.TitleScreen;
Vector2 gameOverPosition = new Vector2(350, 300);
Vector2 livesPosition = new Vector2(600, 580);
Vector2 Velocitys = new Vector2(100, 580);
Texture2D titleScreen;
float deathTimer = 0.0f;
float deathDelay = 5.0f;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
this.graphics.PreferredBackBufferWidth = 800;
this.graphics.PreferredBackBufferHeight = 600;
this.graphics.ApplyChanges();
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
TileMap.Initialize(
Content.Load<Texture2D>(#"Textures\PlatformTiles"));
TileMap.spriteFont =
Content.Load<SpriteFont>(#"Fonts\Pericles8");
pericles8 = Content.Load<SpriteFont>(#"Fonts\Pericles8");
titleScreen = Content.Load<Texture2D>(#"Textures\TitleScreen");
Camera.WorldRectangle = new Rectangle(0, 0, 160 * 48, 12 * 48);
Camera.Position = Vector2.Zero;
Camera.ViewPortWidth = 800;
Camera.ViewPortHeight = 600;
player = new Player(Content);
LevelManager.Initialize(Content, player);
}
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)
this.Exit();
KeyboardState keyState = Keyboard.GetState();
GamePadState gamepadState = GamePad.GetState(PlayerIndex.One);
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
if (gameState == GameState.TitleScreen)
{
if (keyState.IsKeyDown(Keys.Space) ||
gamepadState.Buttons.A == ButtonState.Pressed)
{
StartNewGame();
gameState = GameState.Playing;
}
}
if (gameState == GameState.Playing)
{
player.Update(gameTime);
LevelManager.Update(gameTime);
if (player.Dead)
{
if (player.LivesRemaining > 0)
{
gameState = GameState.PlayerDead;
deathTimer = 0.0f;
}
else{
gameState = GameState.GameOver;
deathTimer = 0.0f;
}
}
}
if (gameState == GameState.PlayerDead)
{
player.Update(gameTime);
LevelManager.Update(gameTime);
deathTimer = elapsed;
if (deathTimer > deathDelay)
{
player.WorldLocation = Vector2.Zero;
LevelManager.ReloadLevel();
player.Revive();
gameState = GameState.Playing;
}
}
if (gameState == GameState.GameOver)
{
deathTimer += elapsed;
if (deathTimer > deathDelay)
{
gameState = GameState.TitleScreen;
}
}
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
// TODO: Add your drawing code here
spriteBatch.Begin(
SpriteSortMode.BackToFront,
BlendState.AlphaBlend);
if (gameState == GameState.TitleScreen)
{
spriteBatch.Draw(titleScreen, Vector2.Zero, Color.White);
}
if ((gameState == GameState.Playing) ||
(gameState == GameState.PlayerDead) ||
(gameState == GameState.GameOver))
{
TileMap.Draw(spriteBatch);
player.Draw(spriteBatch);
LevelManager.Draw(spriteBatch);
spriteBatch.DrawString(
pericles8,
"Score: " + player.Score.ToString(),
scorePosition,
Color.White);
spriteBatch.DrawString(
pericles8,
"Lives Remaining: " + player.LivesRemaining.ToString(),
livesPosition,
Color.White);
spriteBatch.DrawString(
pericles8,
"Velocity: " + GameObject.velocitys.ToString(),
Velocitys,
Color.White);
}
if (gameState == GameState.PlayerDead)
{
}
if (gameState == GameState.GameOver)
{
spriteBatch.DrawString(
pericles8,
"G A M E O V E R !",
gameOverPosition,
Color.White);
}
spriteBatch.End();
base.Draw(gameTime);
}
private void StartNewGame()
{
player.Revive();
player.LivesRemaining = 3;
player.WorldLocation = Vector2.Zero;
LevelManager.LoadLevel(0);
}
}
}
Player.cs:
(A part of the velocity)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;
using Tile_Engine;
namespace **
{
public class Player : GameObject
{
#region Declarations
private Vector2 fallSpeed = new Vector2(0, 20);
private float moveScale = 180.0f;
private bool dead = false;
public int score = 0;
private int livesRemaining = 3;
#endregion
public bool Dead
{
get { return dead; }
}
public int Score
{
get { return score; }
set { score = value; }
}
public int LivesRemaining
{
get { return livesRemaining; }
set { livesRemaining = value; }
}
public void Kill()
{
PlayAnimation("die");
LivesRemaining--;
velocity.X = 0;
dead = true;
}
public void Revive()
{
PlayAnimation("idle");
dead = false;
}
#region Constructor
public Player(ContentManager content)
{
animations.Add("idle",
new AnimationStrip(
content.Load<Texture2D>(#"Textures\Sprites\Player\Idle"),
48,
"idle"));
animations["idle"].LoopAnimation = true;
animations.Add("run",
new AnimationStrip(
content.Load<Texture2D>(#"Textures\Sprites\Player\Run"),
48,
"run"));
animations["run"].LoopAnimation = true;
animations.Add("jump",
new AnimationStrip(
content.Load<Texture2D>(#"Textures\Sprites\Player\Jump"),
48,
"jump"));
animations["jump"].LoopAnimation = false;
animations["jump"].FrameLength = 0.08f;
animations["jump"].NextAnimation = "idle";
animations.Add("die",
new AnimationStrip(
content.Load<Texture2D>(#"Textures\Sprites\Player\Die"),
48,
"die"));
animations["die"].LoopAnimation = false;
frameWidth = 48;
frameHeight = 48;
CollisionRectangle = new Rectangle(9, 1, 30, 46);
drawDepth = 0.825f;
enabled = true;
codeBasedBlocks = false;
PlayAnimation("idle");
}
#endregion
#region Public Methods
public override void Update(GameTime gameTime)
{
if (!Dead)
{
string newAnimation = "idle";
velocity = new Vector2(0, velocity.Y);
GamePadState gamePad = GamePad.GetState(PlayerIndex.One);
KeyboardState keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.Left) ||
(gamePad.ThumbSticks.Left.X < -0.3f))
{
flipped = false;
newAnimation = "run";
velocity = new Vector2(-moveScale, velocity.Y);
}
if (keyState.IsKeyDown(Keys.Right) ||
(gamePad.ThumbSticks.Left.X > 0.3f))
{
flipped = true;
newAnimation = "run";
velocity = new Vector2(moveScale, velocity.Y);
}
if (newAnimation != currentAnimation)
{
PlayAnimation(newAnimation);
}
if (keyState.IsKeyDown(Keys.Space) ||
(gamePad.Buttons.A == ButtonState.Pressed))
{
if (onGround)
{
Jump();
newAnimation = "jump";
}
}
if (currentAnimation == "jump")
newAnimation = "jump";
if (keyState.IsKeyDown(Keys.Up) ||
gamePad.ThumbSticks.Left.Y > 0.3f)
{
checkLevelTransition();
}
}
velocity += fallSpeed;
repositionCamera();
base.Update(gameTime);
}
public void Jump()
{
velocity.Y = -500;
}
#endregion
#region Helper Methods
private void repositionCamera()
{
int screenLocX = (int)Camera.WorldToScreen(worldLocation).X;
if (screenLocX > 500)
{
Camera.Move(new Vector2(screenLocX - 500, 0));
}
if (screenLocX < 200)
{
Camera.Move(new Vector2(screenLocX - 200, 0));
}
}
private void checkLevelTransition()
{
Vector2 centerCell = TileMap.GetCellByPixel(WorldCenter);
if (TileMap.CellCodeValue(centerCell).StartsWith("T_"))
{
string[] code = TileMap.CellCodeValue(centerCell).Split('_');
if (code.Length != 4)
return;
LevelManager.LoadLevel(int.Parse(code[1]));
WorldLocation = new Vector2(
int.Parse(code[2]) * TileMap.TileWidth,
int.Parse(code[3]) * TileMap.TileHeight);
LevelManager.RespawnLocation = WorldLocation;
velocity = Vector2.Zero;
}
}
#endregion
}
}
I have figured out for my self, I mostly wanted a quick answer. Just making a public vector does not help, I needed a method to transfer over the Vector:
public Vector2 Velocitys
{
get { return velocity; }
set { velocity = value; }
}
Then just like the public int Score method I draw it:
spriteBatch.DrawString(
pericles8,
"Velocity: " + player.Velocitys.ToString(),
Velocitys,
Color.White);
It works like a charm.
(Its pretty Ironic that the one thing that I asked why I would use it (get and set) would be the answer)
I have 3 classes:
- Game1 (main class)
- Entity (base entity class)
- Player (player class, extends Entity class)
I draw the player class, but after that I can't seem to change the position of the player object.
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
//Create a list with all the entities
List<Entity> entityList = new List<Entity>();
//Player
Player player;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
//Create player
Texture2D playertexture = Content.Load<Texture2D>("player/player");
Rectangle playerrectangle = new Rectangle(10, 10, playertexture.Width, playertexture.Height);
player = new Player(playertexture, playerrectangle);
entityList.Add(player);
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
this.Exit();
//Update players and entities
player.Update(graphics.GraphicsDevice);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
//Draw player
player.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
class Entity
{
//Standard variables
int health;
int armor;
float speed;
float friction;
//Get graphic and bounding box
Texture2D texture;
Rectangle rectangle;
public Entity(Texture2D newTexture, Rectangle newRectangle){
texture = newTexture;
rectangle = newRectangle;
}
public void Update(GraphicsDevice graphics) {
}
public void Draw(SpriteBatch spriteBatch) {
}
/*
* Modifiers for the variables
*/
public void modifyHealth(int amount) { health = health + amount; }
public void modifyArmor(int amount){ armor = armor + amount; }
public void modifySpeed(float amount) { speed = speed + amount; }
/*
* Getters for variables
*/
public int getHealth() { return health; }
public int getArmor() { return armor; }
public float getSpeed() { return speed; }
public float getFriction() { return friction; }
/*
* Setters for variables
*/
public void setHealth(int amount) { health = amount; }
public void setArmor(int amount) { armor = amount; }
public void setSpeed(float amount) { speed = amount; }
public void setFriction(float amount) { friction = amount; }
/*
* Functions
*/
public void damage(int damage) {
/*
* Calculate health
*
* Armor takes half the damage, if possible
*/
if (damage / 2 >= armor) {
damage = damage / 2;
armor -= damage;
} else if (armor > 0) {
damage -= armor;
armor = 0;
}
health -= damage;
if(health <= 0){
health = 0;
//TODO Death
}
}
}
class Player : Entity
{
//Create player
Entity player;
//Position and velocity
Vector2 position;
Vector2 velocity;
//Texture and rectangle
Texture2D texture;
Rectangle rectangle;
public Player(Texture2D newtexture, Rectangle newrectangle) : base(newtexture, newrectangle) {
texture = newtexture;
rectangle = newrectangle;
//Set basic variables
this.setHealth(100);
this.setArmor(0);
this.setSpeed(10);
this.setFriction(1);
}
public void Update() {
//Movement
if(Keyboard.GetState().IsKeyDown(Keys.Right)){
rectangle.X += 1;
}
rectangle.Y += 4;
}
public void Draw(SpriteBatch spriteBatch) {
spriteBatch.Draw(texture, rectangle, Color.White);
}
}
If there are also general mistakes I make, do point them out, I want to make everything as good as I can now that I'm still learning. Thanks in advance!
Your calling public void Update(GraphicsDevice graphics)
but the movement code is in public void Update()
What I suggest you do is this, use the virtual and override keywords.
In your entity class it should look like this:
public virtual void Update(GraphicsDevice graphics) {
}
And in your player class
public override void Update(GraphicsDevice graphics) {
//ADD MOVEMENT CODE HERE
}
I'm trying to encapsulate my game objects by having them extend Mircosoft.Xna.Framework.GameCompenent, then merely constructing them and managing them in the Update() method of Game1. I have my Game1 class, a Player class, and an Animation class. Animations are supposed manage the Texture2D changes of an object, in this instance Player.
My problem is that even though I have successfully extended everything, have no syntax errors, no exceptions thrown, and have checked and re-checked what little code I have written, the override functions are not called and I end up with a black screen.
Game1.cs: (note that the only two lines changed are for the Player declaration)
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Player player;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
player = new Player(this);
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
base.Draw(gameTime);
}
}
Player.cs:
class Player : Microsoft.Xna.Framework.DrawableGameComponent
{
Rectangle bounds;
Texture2D t;
Animation[] animations = new Animation[4];
String path = #"..\..\..\Content\player.png";
#region Animation Constants
private const int WALK_RIGHT = 0;
#endregion
SpriteBatch spriteBatch;
public Player(Game game) : base(game)
{
//should only ever be one player, all value defaults set in Initialize()
}
public Texture2D T
{
get { return t; }
}
public Rectangle Bounds
{
get { return bounds; }
}
public override void Initialize()
{
base.Initialize();
bounds = new Rectangle(0, 0,
System.Drawing.Image.FromFile(path).Width,
System.Drawing.Image.FromFile(path).Height
);
t = Game.Content.Load<Texture2D>("player");
animations[0] = new Animation(this.Game, "player", "walking", 3);
}
protected override void LoadContent()
{
base.LoadContent();
spriteBatch = new SpriteBatch(this.Game.GraphicsDevice);
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
KeyboardState k = Keyboard.GetState();
if (k.IsKeyDown(Keys.Right)) //walk right
{
bounds.X += 3;
if (animations[WALK_RIGHT].Playing)
{
t = animations[WALK_RIGHT].getTexture();
}
else
{
animations[WALK_RIGHT].Play();
}
}
else if (animations[WALK_RIGHT].Playing)
animations[WALK_RIGHT].Stop();
}
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
spriteBatch.Begin();
spriteBatch.Draw(t, bounds, Color.White);
spriteBatch.End();
}
}
Animation.cs:
class Animation : Microsoft.Xna.Framework.GameComponent
{
Game game;
String name; //name of default sprite; standing, unmoving, neutral, etc. The rest of the animation sprite names should derive from this
String keyword;
int frameCount;
int delay; //frames between texture change
String[] paths; //texture pathnames generated by the MakePaths() function
int currentFrame = 0;
int delayCount = 0;
bool playing = false;
public Animation(Game associatedGame, String nameVal, String keywordVal, int frameCountVal)
: base(associatedGame)
{
name = nameVal;
keyword = keywordVal;
frameCount = frameCountVal;
paths = MakePaths();
delay = 10;
}
public Animation(Game associatedGame, String nameVal, String keywordVal, int frameCountVal, int delayVal)
: base(associatedGame)
{
name = nameVal;
keyword = keywordVal;
frameCount = frameCountVal;
paths = MakePaths();
delay = delayVal;
}
private String[] MakePaths()
{
//format: name_keyword_anim[i]
//format example: player_walking_anim1
String[] temp = new String[frameCount];
for (int i = 0; i < frameCount; i++)
{
temp[i] = name + "_" + keyword + "_" + "anim" + i.ToString();
}
return temp;
}
public Texture2D getTexture()
{
return Game.Content.Load<Texture2D>(paths[currentFrame]);
}
public void Play()
{
playing = true;
}
public void Stop()
{
currentFrame = 0;
delayCount = 0;
playing = false;
}
public bool Playing
{
get { return playing; }
}
public override void Update(GameTime gameTime)
{
if (playing)
{
if (delayCount == delay)
{
delayCount = 0;
if ((currentFrame + 1) == frameCount) currentFrame = 0;
else currentFrame++;
}
else delayCount++;
}
base.Update(gameTime);
}
public override string ToString()
{
return "params: " + name + "," + keyword + "," + frameCount.ToString() + "\nUsing paths: " + paths;
}
}
The only LoadContent, Initialize, Update, and Draw methods that are called are the ones in Game1. What really baffles me is that I was able to use this technique before without issue. These functions would be called naturally by the Xna update process.
So... why is this?
You need to add game Components to the Components collection to have them called automatically
protected override void Initialize()
{
player = new Player(this);
Components.Add(player);
base.Initialize();
}
See http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.game.components.aspx