The name 'IntroState' does not exist in the current context - c#

I get these three error messages in the switch block of Game1 class but I don't know how to fix them. What is wrong?
The name 'IntroState' does not exist in the current context
The name 'MenuState' does not exist in the current context
The name 'MaingameState' does not exist in the current context
In addition, I get this error message in the Intro class:
The name 'IntroState' does not exist in the current context
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
IState currentState;
public enum GameStates
{
IntroState = 0,
MenuState = 1,
MaingameState = 2,
}
public void ChangeGameState(GameStates newState)
{
switch (newState)
{
case IntroState:
currentState = new Intro(this);
break;
case MenuState:
currentState = new Menu(this);
break;
case MaingameState:
currentState = new Maingame(this);
break;
}
currentState.Load(Content);
}
public GameStates CurrentState
{
get { return currentGameState; }
set { currentGameState = value; }
}
private GameStates currentGameState = GameStates.IntroState;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
currentState = new Intro(this);
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
currentState.Load(Content);
}
protected override void Update(GameTime gameTime)
{
currentState.Update(gameTime);
KeyboardState kbState = Keyboard.GetState();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
currentState.Render(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
public interface IState
{
void Load(ContentManager content);
void Update(GameTime gametime);
void Render(SpriteBatch batch);
}
public class Intro : IState
{
Texture2D Introscreen;
private Game1 game1;
public Intro(Game1 game)
{
game1 = game;
}
public void Load(ContentManager content)
{
Introscreen = content.Load<Texture2D>("intro");
}
public void Update(GameTime gametime)
{
KeyboardState kbState = Keyboard.GetState();
if (kbState.IsKeyDown(Keys.Space))
game1.ChangeGameState(IntroState);
}
public void Render(SpriteBatch batch)
{
batch.Draw(Introscreen, new Rectangle(0, 0, 1280, 720), Color.White);
}
}

An enum value can only be used when prefixed with the type-name:
//case IntroState:
case GameStates.IntroState:
you can never use IntroState on its own.

Try:
switch (newState)
{
case GameStates.IntroState:
currentState = new Intro(this);
break;
case GameStates.MenuState:
currentState = new Menu(this);
break;
case GameStates.MaingameState:
currentState = new Maingame(this);
break;
}
IntroState, MenuState and MaingameState belongs to an enum

You should refer to IntroState as GameStates.IntroState. Same applies to the other two.

Related

Error in code Screen Fade Transition fail

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

soundeffect, XNA 4.0

This is the first time I program a game, I want to creat a sound effect on each time I shot a missile, not playing the sound when the missile is on the screen, just right after the character shooted it. Here is the code. Please help me, I tried to do it the whole night :
class Player
{
Texture2D hero;
Vector2 hero_location;
KeyboardState hero_movement;
int missileREA;
public List<adw> missiles = new List<adw>();
ContentManager takeContent;
public void LoadContent(ContentManager Content)
{
hero = Content.Load<Texture2D>("F5S4");
hero_location = Vector2.Zero;
takeContent = Content;
}
public void ShootMissiles(GameTime gameTime)
{
adw missile = new adw();
missile.LoadContent(takeContent);
missile.missile_location = hero_location + new Vector2(hero.Width /2,-50);
missiles.Add(missile);
shot = missiles;
}
public void Update(GameTime gameTime)
{
hero_movement = Keyboard.GetState();
if (hero_movement.IsKeyDown(Keys.W))
{
hero_location.Y -= 5;
}
if (hero_movement.IsKeyDown(Keys.D))
{
hero_location.X += 5;
}
if (hero_movement.IsKeyDown(Keys.S))
{
hero_location.Y += 3;
}
if (hero_movement.IsKeyDown(Keys.A))
{
hero_location.X -= 5;
}
if (hero_movement.IsKeyDown(Keys.NumPad1))
{
missileREA += gameTime.ElapsedGameTime.Milliseconds;
if (missileREA > 200)
{
missileREA = 0;
ShootMissiles(gameTime);
}
}
foreach (adw missile in missiles)
{
missile.Update(gameTime);
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(hero, hero_location, Color.White);
foreach (adw missile in missiles)
{
missile.Draw(spriteBatch);
}
}
public IEnumerable<adw> ShootMissile { get; set; }
public List<adw> shot { get; set; }
}
This is my Game1.cs, where all of my contents are loaded and drawn to the screen under my control.
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Player player;
SoundEffect missile1;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
player = new Player();
graphics.PreferredBackBufferWidth = 1024;
graphics.PreferredBackBufferHeight = 680;
graphics.ApplyChanges();
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
missile1 = Content.Load<SoundEffect>("missile1");
player.LoadContent(Content);
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
foreach (adw missile in player.missiles)
{
missile1.Play();
}
player.Update(gameTime);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
player.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
And if this is not the place to ask things like this, just tell me. I will do as you advice.
protected override void Update(GameTime gameTime)
{
....
foreach (adw missile in player.missiles)
{
missile1.Play();
}
....
}
Every single frame / tick of your game (I assume this is 60 times a second) you are trying to play your sound for every bullet you currently store a reference to. Basically, you're playing a sound 60+ times a second.
Load your sound within your Player class, exactly in the same way you load your texture. Call Play() on it every time you create a new bullet with ShootMissiles(gameTime);

„menuinterface.Menu.exit' is never assigned to, and will always have its default value null“

How I can use Exit() in another class? I want to use it in the Intro class, but I always get that „menuinterface.Menu.exit' is never assigned to, and will always have its default value null“ error message. What is wrong?
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
private IState currentState;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
currentState = new Intro();
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
currentState.Load(Content);
}
protected override void Update(GameTime gameTime)
{
currentState.Update(gameTime);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
currentState.Render(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
public interface IState
{
void Load(ContentManager content);
void Update(GameTime gametime);
void Render(SpriteBatch batch);
}
public class Intro : IState
{
private IState currentState;
private Game1 exit;
Texture2D introscreen;
public void Load(ContentManager content)
{
introscreen = content.Load<Texture2D>("intro");
}
public void Update(GameTime gametime)
{
KeyboardState kbState = Keyboard.GetState();
if (kbState.IsKeyDown(Keys.Space))
currentState = new Menu();
if (kbState.IsKeyDown(Keys.Escape))
exit.Exit();
}
public void Render(SpriteBatch batch)
{
batch.Draw(introscreen, new Rectangle(0, 0, 1280, 720), Color.White);
}
}
Here's your problem:
public class Intro : IState
{
private IState currentState;
private Game1 exit;
Texture2D introscreen;
public void Load(ContentManager content)
{
introscreen = content.Load<Texture2D>("intro");
}
public void Update(GameTime gametime)
{
KeyboardState kbState = Keyboard.GetState();
if (kbState.IsKeyDown(Keys.Space))
currentState = new Menu();
if (kbState.IsKeyDown(Keys.Escape))
exit.Exit(); // ---- this object does not exist
}
public void Render(SpriteBatch batch)
{
batch.Draw(introscreen, new Rectangle(0, 0, 1280, 720), Color.White);
}
}
In this class you are declaring an object called exit but this value is never assigned. You need to instantiate the object before you use it. In your case, I would add the following constructor to resolve your problem.
public Intro(Game1 game)
{
exit = game;
}
You do not assign anything to your exit object, which appears to be of type Game, so this is why you get this error. But why do you need this exit object in the first place?
If you want to quit the game after pressing Escape, use Exit() method. It doesn't require you to use it like in your code. It is as simple as this:
public class Game1 : Microsoft.Xna.Framework.Game
{
// ...
protected override void Update(GameTime gameTime)
{
if (kbState.IsKeyDown(Keys.Escape))
Exit();
base.Update(gameTime);
}
// ...
}

Cant Load Content When Not In Main Game Class

public class Dirt : Tile
{
Vector2 position;
Texture2D texture;
public Dirt(Game game, Vector2 Position)
: base(game)
{
type = "dirt";
textureName = "Textures/Dirt";
position = Position;
}
public override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
texture = Salvage.contentManager.Load<Texture2D>("Textures/Dirt"); // This doesnt work
base.LoadContent();
}
public override void Update(GameTime gameTime)
{
if (InputHandler.KeyDown(Keys.W))
{
position.Y -= 1;
}
else if (InputHandler.KeyDown(Keys.S))
{
position.Y += 1;
}
if (InputHandler.KeyDown(Keys.D))
{
position.X += 1;
}
else if (InputHandler.KeyDown(Keys.A))
{
position.X -= 1;
}
Camera.DesiredPosition = position;
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
Salvage.spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, Camera.Transformation);
Salvage.spriteBatch.Draw(texture, position, Color.White);
Salvage.spriteBatch.End();
base.Draw(gameTime);
}
}
The loading seems to work fine if i load it in the Salvage class(Main game class)
Edit:
The error im getting is:
Salvage.spriteBatch.Draw(texture, position, Color.White);
This method does not accept null for this parameter.
Parameter name: texture
Here is the code for Salvage class:
public class Salvage : Microsoft.Xna.Framework.Game
{
public static GraphicsDeviceManager graphics;
public static SpriteBatch spriteBatch;
public static ContentManager contentManager;
public static SpriteFont spriteFont;
public GameStateManager stateManager;
public Rectangle ScreenRectangle = new Rectangle(0, 0, 1024, 768);
public Salvage()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferHeight = ScreenRectangle.Height;
graphics.PreferredBackBufferWidth = ScreenRectangle.Width;
Content.RootDirectory = "Content";
contentManager = Content;
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
spriteFont = Content.Load<SpriteFont>("Fonts/DefaultSpriteFont"); // This works fine
stateManager = new GameStateManager(this);
GameplayState gameplayState = new GameplayState(this, stateManager);
Components.Add(new InputHandler(this));
Components.Add(new Camera(this, ScreenRectangle));
Components.Add(stateManager);
stateManager.ChangeState(gameplayState);
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || InputHandler.KeyReleased(Keys.Escape))
this.Exit();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
base.Draw(gameTime);
}
}
And the code for Tile
public abstract class Tile : Microsoft.Xna.Framework.DrawableGameComponent
{
public string textureName;
public string type;
public Tile(Game game)
: base(game)
{
}
public override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
base.LoadContent();
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
}
}
Edit:
Here is the GamePlayState class
public class GameplayState : GameState
{
public GameplayState(Game game, GameStateManager manager)
: base(game, manager)
{
childGameComponents.Add(new Dirt(game, new Vector2(0, 0)));
}
public override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
base.LoadContent();
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
}
public override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
}
}
I have seen your problem. You declare the contentManager variable, but you never assign it until the LoadContent method. If you are loading Dirt before this, you won't have a valid ContentManager variable causing it to fail.
In your constructor of your Salvage class, add the following line:
contentManager = Content;
This should resolve your issue.

XNA: Basic DrawableGameComponent override functions (Update, Draw, etc) not being called

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

Categories

Resources