Jump to content

  • Log In with Google      Sign In   
  • Create Account


XNA C# Help with HUD


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
10 replies to this topic

#1 Key   Members   -  Reputation: 112

Like
0Likes
Like

Posted 20 September 2011 - 08:18 PM

I had my HUD drawn to the screen and it's Vector2 set to the camera's position, HUD followed along with the camera just fine.
I then went ahead and created a class just for the HUD, but it doesn't seem to get the camera's position now.


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.Input;
using GameOne.Components;

namespace GameOne.GameScreens
{
	public class HUD : BaseGameState
	{
    	Player player;

    	Texture2D HealthBar;
    	Texture2D HealthBarPositive;
    	Texture2D HealthBarNegative;
    	Texture2D ManaBar;
    	Texture2D ManaBarPositive;
    	Texture2D ManaBarNegative;
    	Texture2D ExpBar;
    	Texture2D ExpBarPositive;

    	int CurrentHealth = 100;
    	int CurrentMana = 45;
    	int CurrentExp = 0;

    	public HUD(Game game, GameStateManager manager)
        	: base(game, manager)
    	{
        	player = new Player(game);
    	}

    	public void LoadContent()
    	{
        	base.LoadContent();

        	HealthBar = Game.Content.Load<Texture2D>(@"GUI\healthBar");
        	HealthBarPositive = Game.Content.Load<Texture2D>(@"GUI\healthBarPositive");
        	HealthBarNegative = Game.Content.Load<Texture2D>(@"GUI\healthBarNegative");
        	ManaBar = Game.Content.Load<Texture2D>(@"GUI\manaBar");
        	ManaBarPositive = Game.Content.Load<Texture2D>(@"GUI\manaBarPositive");
        	ManaBarNegative = Game.Content.Load<Texture2D>(@"GUI\manaBarNegative");
        	ExpBar = Game.Content.Load<Texture2D>(@"GUI\expBar");
        	ExpBarPositive = Game.Content.Load<Texture2D>(@"GUI\expBarPositive");
    	}

    	public override void Update(GameTime gameTime)
    	{
        	if (InputHandler.KeyDown(Keys.F1))
        	{
            	CurrentHealth += 1;
        	}

        	if (InputHandler.KeyDown(Keys.F2))
        	{
            	CurrentHealth -= 1;
        	}

        	if (InputHandler.KeyDown(Keys.F3))
        	{
            	CurrentMana += 1;
        	}

        	if (InputHandler.KeyDown(Keys.F4))
        	{
            	CurrentMana -= 1;
        	}

        	if (InputHandler.KeyDown(Keys.F5))
        	{
            	CurrentExp += 1;
        	}

        	if (InputHandler.KeyDown(Keys.F6))
        	{
            	CurrentExp -= 1;
        	}

        	CurrentHealth = (int)MathHelper.Clamp(CurrentHealth, 0, 100);
        	CurrentMana = (int)MathHelper.Clamp(CurrentMana, 0, 45);
        	CurrentExp = (int)MathHelper.Clamp(CurrentExp, 0, 500);
    	}

    	public override void Draw(GameTime gameTime)
    	{
        	GameRef.SpriteBatch.Draw(
            	HealthBarNegative,
            	new Rectangle((int)player.Camera.Position.X + 150, (int)player.Camera.Position.Y + 630, 150, 15),
            	Color.White);

        	GameRef.SpriteBatch.Draw(
            	HealthBarPositive,
            	new Rectangle((int)player.Camera.Position.X + 150, (int)player.Camera.Position.Y + 630, 150 * (int)CurrentHealth / 100, 15),
            	Color.White);

        	GameRef.SpriteBatch.Draw(
            	HealthBar,
            	new Rectangle((int)player.Camera.Position.X + 150, (int)player.Camera.Position.Y + 630, 150, 15),
            	Color.White);

        	GameRef.SpriteBatch.Draw(
            	ManaBarNegative,
            	new Rectangle((int)player.Camera.Position.X + 150, (int)player.Camera.Position.Y + 650, 150, 15),
            	Color.White);

        	GameRef.SpriteBatch.Draw(
            	ManaBarPositive,
            	new Rectangle((int)player.Camera.Position.X + 150, (int)player.Camera.Position.Y + 650, 150 * (int)CurrentMana / 45, 15),
            	Color.White);

        	GameRef.SpriteBatch.Draw(
            	ManaBar,
            	new Rectangle((int)player.Camera.Position.X + 150, (int)player.Camera.Position.Y + 650, 150, 15),
            	Color.White);

        	GameRef.SpriteBatch.Draw(
            	ExpBarPositive,
            	new Rectangle((int)player.Camera.Position.X + 10, (int)player.Camera.Position.Y + 680, 1260 * (int)CurrentExp / 500, 15),
            	Color.White);

        	GameRef.SpriteBatch.Draw(
            	ExpBar,
            	new Rectangle((int)player.Camera.Position.X + 10, (int)player.Camera.Position.Y + 680, 1260, 15),
            	Color.White);
    	}
	}
}



Sponsor:

#2 BCullis   Crossbones+   -  Reputation: 1813

Like
0Likes
Like

Posted 22 September 2011 - 01:16 PM

What does the constructor for your Player class look like?
(I.e. how does it pull player information from the passed game reference?)
Hazard Pay :: FPS/RTS in SharpDX
DeviantArt :: Because right-brain needs love too

#3 Key   Members   -  Reputation: 112

Like
0Likes
Like

Posted 22 September 2011 - 05:20 PM

Player.cs
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.Input;
using GameOne.TileEngine;

namespace GameOne.Components
{
	public class Player
	{
    	Camera camera;
    	Game1 gameRef;

    	public Camera Camera
    	{
        	get { return camera; }
        	set { camera = value; }
    	}

    	public Player(Game game)
    	{
        	gameRef = (Game1)game;
        	camera = new Camera(gameRef.ScreenRectangle);
    	}

    	public void Update(GameTime gameTime)
    	{
        	camera.Update(gameTime);
    	}

    	public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
    	{
    	}
	}
}

Camera.cs
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.Input;
using GameOne.SpriteClasses;

namespace GameOne.TileEngine
{
	public enum CameraMode { Free, Follow }

	public class Camera
	{
    	Vector2 position;
    	float speed;
    	float zoom;
    	Rectangle viewportRectangle;
    	CameraMode mode;

    	public Vector2 Position
    	{
        	get { return position; }
        	private set { position = value; }
    	}

    	public float Speed
    	{
        	get { return speed; }
        	set
        	{
            	speed = (float)MathHelper.Clamp(speed, 1f, 16f);
        	}
    	}

    	public float Zoom
    	{
        	get { return zoom; }
    	}

    	public CameraMode CameraMode
    	{
        	get { return mode; }
    	}

    	public Matrix Transformation
    	{
        	get { return Matrix.CreateScale(zoom) * Matrix.CreateTranslation(new Vector3(-Position, 0f)); }
    	}

    	public Rectangle ViewportRectangle
    	{
        	get
        	{
            	return new Rectangle(
                	viewportRectangle.X,
                	viewportRectangle.Y,
                	viewportRectangle.Width,
                	viewportRectangle.Height);
        	}
    	}

    	public Camera(Rectangle viewportRect)
    	{
        	speed = 4f;
        	zoom = 1f;
        	viewportRectangle = viewportRect;
        	mode = CameraMode.Follow;
    	}

    	public Camera(Rectangle viewportRect, Vector2 position)
    	{
        	speed = 4f;
        	zoom = 1f;
        	viewportRectangle = viewportRect;
        	Position = position;
        	mode = CameraMode.Follow;
    	}

    	public void Update(GameTime gameTime)
    	{
        	if (mode == CameraMode.Follow)
            	return;

        	Vector2 motion = Vector2.Zero;

        	if (InputHandler.KeyDown(Keys.Left))
            	motion.X -= speed;
        	else if (InputHandler.KeyDown(Keys.Right))
            	motion.X += speed;

        	if (InputHandler.KeyDown(Keys.Up))
            	motion.Y -= speed;
        	else if (InputHandler.KeyDown(Keys.Down))
            	motion.Y += speed;

        	if (motion != Vector2.Zero)
        	{
            	motion.Normalize();
            	position += motion * speed;
            	LockCamera();
        	}
    	}

    	private void LockCamera()
    	{
        	position.X = MathHelper.Clamp(
            	position.X,
            	0,
            	TileMap.WidthInPixels * zoom - viewportRectangle.Width);

        	position.Y = MathHelper.Clamp(
            	position.Y,
            	0,
            	TileMap.HeightInPixels * zoom - viewportRectangle.Height);
    	}

    	public void LockToSprite(AnimatedSprite sprite)
    	{
        	position.X = (sprite.Position.X + sprite.Width / 2) * zoom - (viewportRectangle.Width / 2);
        	position.Y = (sprite.Position.Y + sprite.Height / 2) * zoom - (viewportRectangle.Height / 2);
        	LockCamera();
    	}

    	public void ToggleCameraMode()
    	{
        	if (mode == CameraMode.Follow)
            	mode = CameraMode.Free;
        	else if (mode == CameraMode.Free)
            	mode = CameraMode.Follow;
    	}

    	public void ZoomIn()
    	{
        	zoom += 0.25f;

        	if (zoom > 2.5f)
            	zoom = 2.5f;

        	Vector2 newPosition = Position * zoom;
        	SnapToPosition(newPosition);
    	}

    	public void ZoomOut()
    	{
        	zoom -= 0.25f;

        	if (zoom < 0.5f)
            	zoom = 0.5f;

        	Vector2 newPosition = Position * zoom;
        	SnapToPosition(newPosition);
    	}

    	private void SnapToPosition(Vector2 newPosition)
    	{
        	position.X = newPosition.X - viewportRectangle.Width / 2;
        	position.Y = newPosition.Y - viewportRectangle.Height / 2;
        	LockCamera();
    	}
	}
}


#4 laztrezort   Members   -  Reputation: 954

Like
1Likes
Like

Posted 22 September 2011 - 07:34 PM

Some thoughts:

Where is the Camera position being updated? I see the HUD class creates a Player, but doesn't expose it as a public property (or field), so how/where does the Player.Camera get used? Are you sure you don't have 2 separate Player instances floating around somewhere, and are updating the wrong one?

When you put a breakpoint here

        	GameRef.SpriteBatch.Draw(
     				HealthBarNegative,
     				new Rectangle((int)player.Camera.Position.X + 150, (int)player.Camera.Position.Y + 630, 150, 15),
     				Color.White);

what value does player.Camera.Position.X have (and what are you expecting it to have)?

Put a breakpoint at "set" here

        public Camera Camera
        {
                get { return camera; }
----> 		set { camera = value; }
        }

Does this get called when you predict it to?

Have you tried just stepping through your logic with the Debugger? These types of bugs are usually easy to find just by stepping through code, examining variables, etc, especially in a language like C# which has few surprises.

#5 Key   Members   -  Reputation: 112

Like
0Likes
Like

Posted 22 September 2011 - 08:06 PM

GamePlayScreen.cs is where it's being updated and it seems I do have two instances of Player.
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.Input;
using GameOne.TileEngine;
using GameOne.Components;
using GameOne.SpriteClasses;
using GameOne.Controls;

namespace GameOne.GameScreens
{
	public class GamePlayScreen : BaseGameState
	{
    	Engine engine = new Engine(32, 32);
    	TileMap map;
    	Player player;
    	AnimatedSprite sprite;
    	HUD hud;

    	public GamePlayScreen(Game game, GameStateManager manager)
        	: base(game, manager)
    	{
        	player = new Player(game);
        	hud = new HUD(game, manager);
    	}

    	public override void Initialize()
    	{
        	base.Initialize();
    	}

    	protected override void LoadContent()
    	{
        	Texture2D spriteSheet = Game.Content.Load<Texture2D>(@"PlayerSprites\" + GameRef.CharacterCreationScreen.SelectedGender + GameRef.CharacterCreationScreen.SelectedClass);
        	Dictionary<AnimationKey, Animation> animations = new Dictionary<AnimationKey, Animation>();

        	Animation animation = new Animation(3, 32, 32, 0, 0);
        	animations.Add(AnimationKey.Down, animation);

        	animation = new Animation(3, 32, 32, 0, 32);
        	animations.Add(AnimationKey.Left, animation);

        	animation = new Animation(3, 32, 32, 0, 64);
        	animations.Add(AnimationKey.Right, animation);

        	animation = new Animation(3, 32, 32, 0, 96);
        	animations.Add(AnimationKey.Up, animation);

        	sprite = new AnimatedSprite(spriteSheet, animations);

        	base.LoadContent();

        	Texture2D tilesetTexture = Game.Content.Load<Texture2D>(@"Tilesets\tilesetOne");
        	Tileset tileset1 = new Tileset(tilesetTexture, 8, 8, 32, 32);

        	tilesetTexture = Game.Content.Load<Texture2D>(@"Tilesets\tilesetTwo");
        	Tileset tileset2 = new Tileset(tilesetTexture, 8, 8, 32, 32);

        	List<Tileset> tilesets = new List<Tileset>();
        	tilesets.Add(tileset1);
        	tilesets.Add(tileset2);

        	MapLayer layer = new MapLayer(50, 50);

        	for (int y = 0; y < layer.Height; y++)
        	{
            	for (int x = 0; x < layer.Width; x++)
            	{
                	Tile tile = new Tile(0, 0);

                	layer.SetTile(x, y, tile);
            	}
        	}

        	MapLayer splatter = new MapLayer(50, 50);

        	Random random = new Random();

        	for (int i = 0; i < 160; i++)
        	{
            	int x = random.Next(0, 50);
            	int y = random.Next(0, 50);
            	int index = random.Next(2, 6);

            	Tile tile = new Tile(index, 0);
            	splatter.SetTile(x, y, tile);
        	}

        	splatter.SetTile(1, 0, new Tile(0, 1));
        	splatter.SetTile(2, 0, new Tile(1, 1));
        	splatter.SetTile(3, 0, new Tile(0, 1));
        	splatter.SetTile(2, 1, new Tile(2, 1));

        	List<MapLayer> mapLayers = new List<MapLayer>();
        	mapLayers.Add(layer);
        	mapLayers.Add(splatter);

        	map = new TileMap(tilesets, mapLayers);

        	hud.LoadContent();
    	}

    	public override void Update(GameTime gameTime)
    	{
        	player.Update(gameTime);
        	sprite.Update(gameTime);
        	hud.Update(gameTime);

        	if (InputHandler.KeyReleased(Keys.Add))
        	{
            	player.Camera.ZoomIn();
            	if (player.Camera.CameraMode == CameraMode.Follow)
                	player.Camera.LockToSprite(sprite);
        	}
        	else if (InputHandler.KeyReleased(Keys.Subtract))
        	{
            	player.Camera.ZoomOut();
            	if (player.Camera.CameraMode == CameraMode.Follow)
                	player.Camera.LockToSprite(sprite);
        	}

        	Vector2 motion = new Vector2();

        	if (InputHandler.KeyDown(Keys.W))
        	{
            	sprite.CurrentAnimation = AnimationKey.Up;
            	motion.Y = -1;
        	}
        	else if (InputHandler.KeyDown(Keys.S))
        	{
            	sprite.CurrentAnimation = AnimationKey.Down;
            	motion.Y = 1;
        	}

        	if (InputHandler.KeyDown(Keys.A))
        	{
            	sprite.CurrentAnimation = AnimationKey.Up;
            	motion.X = -1;
        	}
        	else if (InputHandler.KeyDown(Keys.D))
        	{
            	sprite.CurrentAnimation = AnimationKey.Down;
            	motion.X = 1;
        	}

        	if (motion != Vector2.Zero)
        	{
            	sprite.IsAnimating = true;
            	motion.Normalize();

            	sprite.Position += motion * sprite.Speed;
            	sprite.LockToMap();

            	if (player.Camera.CameraMode == CameraMode.Follow)
                	player.Camera.LockToSprite(sprite);
        	}
        	else
        	{
            	sprite.IsAnimating = false;
        	}

        	if (InputHandler.KeyReleased(Keys.F))
        	{
            	player.Camera.ToggleCameraMode();
            	if (player.Camera.CameraMode == CameraMode.Follow)
                	player.Camera.LockToSprite(sprite);
        	}

        	if (player.Camera.CameraMode != CameraMode.Follow)
        	{
            	if (InputHandler.KeyReleased(Keys.C))
            	{
                	player.Camera.LockToSprite(sprite);
            	}
        	}

        	base.Update(gameTime);
    	}

    	public override void Draw(GameTime gameTime)
    	{
        	GameRef.SpriteBatch.Begin(
            	SpriteSortMode.Deferred,
            	BlendState.AlphaBlend,
            	SamplerState.PointClamp,
            	null,
            	null,
            	null,
            	player.Camera.Transformation);

        	map.Draw(GameRef.SpriteBatch, player.Camera);

        	sprite.Draw(gameTime, GameRef.SpriteBatch, player.Camera);

        	hud.Draw(gameTime);

        	base.Draw(gameTime);

        	GameRef.SpriteBatch.End();
    	}
	}
}

I think the value for player.Camera.Position is zero.
I want it equal to the camera's position so the HUD tracks along with the camera as it pans.

#6 laztrezort   Members   -  Reputation: 954

Like
1Likes
Like

Posted 22 September 2011 - 08:18 PM

Pass the player instance from your GamePlayScreen to your HUD instance so that they are both using the same player.camera object. You could modify the constructor for HUD so it takes a Player as a parameter, then store that in your HUD instance instead of creating a new one. Then you'd do something like this

public GamePlayScreen(Game game, GameStateManager manager)
 	: base(game, manager)
   	{
        	player = new Player(game);
        	hud = new HUD(game, manager, player);
   	}

Do you understand why this must done?

#7 Key   Members   -  Reputation: 112

Like
0Likes
Like

Posted 22 September 2011 - 08:51 PM

Don't completely understand it, but I will go research some more after dinner.

I modified the HUD constructor like so:
public HUD(Game game, GameStateManager manager, Player player)
        	: base(game, manager)
    	{

    	}

I tried adding and removing stuff, but I'm getting 'Object not set to an instance of an object'

#8 laztrezort   Members   -  Reputation: 954

Like
1Likes
Like

Posted 22 September 2011 - 09:09 PM

You need to set the HUD.player member to the Player parameter you pass to it, like so:

public HUD(Game game, GameStateManager manager, Player player)
        	: base(game, manager)
    	{
              this.player = player;
    	}

This way, the HUD.player references the same Player object as the one you create in your GamePlayState object. This way they are the same object (the same chunk of memory), so anything you do to HUD.player will be the same as doing it to the Player instance you pass into the HUD constructor (and vice versa).

Sorry if I'm not explaining it well enough - you would probably do better to read up on classes (reference types) and structs (value types) and what their differences are. While you are at it, look into pass-by-reference and pass-by-value, since despite the similar names these are different concepts, and are important to understand up-front.

#9 Key   Members   -  Reputation: 112

Like
0Likes
Like

Posted 22 September 2011 - 09:52 PM

You need to set the HUD.player member to the Player parameter you pass to it, like so:

public HUD(Game game, GameStateManager manager, Player player)
        	: base(game, manager)
    	{
              this.player = player;
    	}

This way, the HUD.player references the same Player object as the one you create in your GamePlayState object. This way they are the same object (the same chunk of memory), so anything you do to HUD.player will be the same as doing it to the Player instance you pass into the HUD constructor (and vice versa).

Sorry if I'm not explaining it well enough - you would probably do better to read up on classes (reference types) and structs (value types) and what their differences are. While you are at it, look into pass-by-reference and pass-by-value, since despite the similar names these are different concepts, and are important to understand up-front.


You did a pretty good job explaining it. I understand, using the same object for both HUD and GamePlayScreen, for the the most part. It just takes a while for me to understand it and piece it together.
I will take a look into all of those. Thanks for helping me!

#10 Key   Members   -  Reputation: 112

Like
0Likes
Like

Posted 24 September 2011 - 09:30 PM

I added a spritefont to my HUD and this is what I get:
Posted Image

All those white spots are from my camera panning and the text following along.
What's going on?
Label displayName = new Label();

        	displayName.Text = "DisplayName";
        	displayName.Size = displayName.SpriteFont.MeasureString(displayName.Text);
        	displayName.Position = new Vector2((int)player.Camera.Position.X, (int)player.Camera.Position.Y);

        	ControlManager.Add(displayName);

        	ControlManager.Draw(GameRef.SpriteBatch);


#11 Key   Members   -  Reputation: 112

Like
0Likes
Like

Posted 04 October 2011 - 09:46 PM

public override void Draw(GameTime gameTime)
    	{
        	GameRef.SpriteBatch.Begin(
            	SpriteSortMode.Deferred,
            	BlendState.AlphaBlend,
            	SamplerState.PointClamp,
            	null,
            	null,
            	null,
            	player.Camera.Transformation);

        	map.Draw(GameRef.SpriteBatch, player.Camera);

        	sprite.Draw(gameTime, GameRef.SpriteBatch, player.Camera);

        	hud.Draw(gameTime);

        	base.Draw(gameTime);

        	GameRef.SpriteBatch.End();
    	}


I found out that I was constantly drawing the spritefont every frame.
Is there anyway I can work around this? Just like what I did with my status bars.
Or is there an alternative to using Camera Transformation for my positions?




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS