Changing the sprite image in XNA - c#

This is my code for the movement of my sprite for my game. I looked at tutorials and lessons on line to help me with this. I need to know how to make the character sprite change every time a certain key is pressed. (eg. left key: left facing sprite, right key: right facing sprite) I have looked on line but I;m not sure how to integrate it into my code. I believe I can do something with the enumerated list in my "MageChar" class to change the sprite but i'm not sure how to begin. Any help is appreciated.
Game Class
namespace RPG
{
public class MageChar : charMovement
{
//variable where sprite file name is stored
const string MageAssetName = "MageChar";
//starting x position
const int StartPositionX = 0;
//starting y position
const int StartPositionY = 0;
//speed that the sprite will move on screen
const int MageSpeed = 160;
//move sprite 1 up/down when the arrow key is pressed
const int MoveUp = 1;
const int MoveDown = -1;
const int MoveLeft = -1;
const int MoveRight = 1;
//used to store the current state of the sprite
enum State
{
Walking
}
//set to current state of the sprite. initally set to walking
State CurrentState = State.Walking;
//stores direction of sprite
Vector2 Direction = Vector2.Zero;
//stores speed of sprite
Vector2 Speed = Vector2.Zero;
//stores previous state of keyboard
KeyboardState PreviousKeyboardState;
public void LoadContent(ContentManager theContentManager)
{
//sets position to the top left corner of the screen
Position = new Vector2(StartPositionX, StartPositionY);
base.LoadContent(theContentManager, MageAssetName);
}
//checks state of the keyboard
private void UpdateMovement(KeyboardState aCurrentKeyboardState)
{
//run if the sprite is walking
if (CurrentState == State.Walking)
{
//sets direction and speed to zero
Speed = Vector2.Zero;
Direction = Vector2.Zero;
//if left key is pressed, move left
if (aCurrentKeyboardState.IsKeyDown(Keys.Left) == true)
{
//speed of sprite movement
Speed.X = MageSpeed;
//moves the sprite left
Direction.X = MoveLeft;
}
//if right key is pressed, move right
else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) == true)
{
//speed of sprite movement
Speed.X = MageSpeed;
//moves the sprite right
Direction.X = MoveRight;
}
//if up key is pressed, move up
if (aCurrentKeyboardState.IsKeyDown(Keys.Up) == true)
{
//speed of sprite movement
Speed.Y = MageSpeed;
//moves sprite up
Direction.Y = MoveUp;
}
//if down key is pressed, move down
else if (aCurrentKeyboardState.IsKeyDown(Keys.Down) == true)
{
//speed of sprite movement
Speed.Y = MageSpeed;
//moves sprite down
Direction.Y = MoveDown;
}
}
}
public void Update(GameTime theGameTime)
{
//obtains current state of the keyboard
KeyboardState aCurrentKeyboardState = Keyboard.GetState();
//calls in UpdateMovement and passes in current keyboard state
UpdateMovement(aCurrentKeyboardState);
//set previous state to current state
PreviousKeyboardState = aCurrentKeyboardState;
//call update method of the charMovement class
base.Update(theGameTime, Speed, Direction);
}
}
}
CharMovement
namespace RPG
{
public class charMovement
{
//The asset name for the Sprite's Texture
public string charSprite;
//The Size of the Sprite (with scale applied)
public Rectangle Size;
//The amount to increase/decrease the size of the original sprite.
private float mScale = 1.0f;
//The current position of the Sprite
public Vector2 Position = new Vector2(0,0);
//The texture object used when drawing the sprite
private Texture2D charTexture;
//Load the texture for the sprite using the Content Pipeline
public void LoadContent(ContentManager theContentManager, string theCharSprite)
{
//loads the image of the sprite
charTexture = theContentManager.Load<Texture2D>("charSprite");
charSprite = theCharSprite;
//creates a new rectangle the size of the sprite
Size = new Rectangle(0, 0, (int)(charTexture.Width * mScale), (int)(charTexture.Height * mScale));
}
//Update the Sprite and change it's position based on the set speed, direction and elapsed time.
public void Update(GameTime theGameTime, Vector2 theSpeed, Vector2 theDirection)
{
Position += theDirection * theSpeed * (float)theGameTime.ElapsedGameTime.TotalSeconds;
}
//Draw the sprite to the screen
public void Draw(SpriteBatch theSpriteBatch)
{
//draw the sprite to the screen inside a rectangle
theSpriteBatch.Draw(charTexture, Position,
new Rectangle(0, 0, charTexture.Width, charTexture.Height),
Color.White, 0.0f, Vector2.Zero, mScale, SpriteEffects.None, 0);
}
}
}
MageChar
namespace RPG
{
public class MageChar : charMovement
{
//variable where sprite file name is stored
const string MageAssetName = "MageChar";
//starting x position
const int StartPositionX = 0;
//starting y position
const int StartPositionY = 0;
//speed that the sprite will move on screen
const int MageSpeed = 160;
//move sprite 1 up/down when the arrow key is pressed
const int MoveUp = 1;
const int MoveDown = -1;
const int MoveLeft = -1;
const int MoveRight = 1;
//used to store the current state of the sprite
enum State
{
Walking
}
//set to current state of the sprite. initally set to walking
State CurrentState = State.Walking;
//stores direction of sprite
Vector2 Direction = Vector2.Zero;
//stores speed of sprite
Vector2 Speed = Vector2.Zero;
//stores previous state of keyboard
KeyboardState PreviousKeyboardState;
public void LoadContent(ContentManager theContentManager)
{
//sets position to the top left corner of the screen
Position = new Vector2(StartPositionX, StartPositionY);
base.LoadContent(theContentManager, MageAssetName);
}
//checks state of the keyboard
private void UpdateMovement(KeyboardState aCurrentKeyboardState)
{
//run if the sprite is walking
if (CurrentState == State.Walking)
{
//sets direction and speed to zero
Speed = Vector2.Zero;
Direction = Vector2.Zero;
//if left key is pressed, move left
if (aCurrentKeyboardState.IsKeyDown(Keys.Left) == true)
{
//speed of sprite movement
Speed.X = MageSpeed;
//moves the sprite left
Direction.X = MoveLeft;
}
//if right key is pressed, move right
else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) == true)
{
//speed of sprite movement
Speed.X = MageSpeed;
//moves the sprite right
Direction.X = MoveRight;
}
//if up key is pressed, move up
if (aCurrentKeyboardState.IsKeyDown(Keys.Up) == true)
{
//speed of sprite movement
Speed.Y = MageSpeed;
//moves sprite up
Direction.Y = MoveUp;
}
//if down key is pressed, move down
else if (aCurrentKeyboardState.IsKeyDown(Keys.Down) == true)
{
//speed of sprite movement
Speed.Y = MageSpeed;
//moves sprite down
Direction.Y = MoveDown;
}
}
}
public void Update(GameTime theGameTime)
{
//obtains current state of the keyboard
KeyboardState aCurrentKeyboardState = Keyboard.GetState();
//calls in UpdateMovement and passes in current keyboard state
UpdateMovement(aCurrentKeyboardState);
//set previous state to current state
PreviousKeyboardState = aCurrentKeyboardState;
//call update method of the charMovement class
base.Update(theGameTime, Speed, Direction);
}
}
}

First you need to create sprite texture: put all images of your character in one texture (like this: https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTl7XCFrVrnkzcNtpokcpJf3SKxcALw-IpbuSgVP4xNRBgtsnN4). Lets say that for now your character have two different states - facing left and facing right and both textures is 64x64. So we have something like this:
-----------------
| | |
| <-- | --> |
| | |
-----------------
Total texture size: 128x64
You need to add more values to state enum. Lets say your state enum will have two values Left and Right instead of just Walking.
Now you can switch frames in your draw method using third parameter:
if (CurrentState == State.Left)
theSpriteBatch.Draw(charTexture, Position,
new Rectangle(0, 0, 64, 64), // first frame
Color.White, 0.0f, Vector2.Zero, mScale, SpriteEffects.None, 0);
else if (CurrentState == State.Right)
theSpriteBatch.Draw(charTexture, Position,
new Rectangle(64, 0, 64, 64), // second frame
Color.White, 0.0f, Vector2.Zero, mScale, SpriteEffects.None, 0);
You also can use direction or anything you want instead of state. In the future you would want to have different textures for whole walking animation and other actions for single character.
More about sprite animations: http://thundernoodle.net/notblog/2011/10/17/how-to-animate-a-sprite-using-a-sprite-sheet-in-xna/
You can also switch textures, as suggested, for different states. To do so just load two different textures, for example charTexture_Left and charTexture_Right and use them in draw method depending on CurrentState.
To make CurrentState change along with a user arrow input add CurrentState to UpdateMovement method:
if (aCurrentKeyboardState.IsKeyDown(Keys.Left) == true)
{
//speed of sprite movement
Speed.X = MageSpeed;
//moves the sprite left
Direction.X = MoveLeft;
CurrentState = State.Left; // set current state to left
}
else if (aCurrentKeyboardState.IsKeyDown(Keys.Right) == true)
{
//speed of sprite movement
Speed.X = MageSpeed;
//moves the sprite right
Direction.X = MoveRight;
CurrentState = State.Right; // set current state to right
}

Related

Unity Pan and Zoom. Camera translate changes entirely once i click on screen

I'm trying to set Panning and zooming functions for my unity project. I got the codes i used from https://kylewbanks.com/blog/unity3d-panning-and-pinch-Ito-zoom-camera-with-touch-and-mouse-input. This is the code I used:
using UnityEngine;
using System.Collections;
public class CameraHandler : MonoBehaviour {
private static readonly float PanSpeed = 20f;
private static readonly float ZoomSpeedTouch = 0.1f;
private static readonly float ZoomSpeedMouse = 0.5f;
private static readonly float[] BoundsX = new float[]{-10f, 5f};
private static readonly float[] BoundsZ = new float[]{-18f, -4f};
private static readonly float[] ZoomBounds = new float[]{10f, 85f};
private Camera cam;
private Vector3 lastPanPosition;
private int panFingerId; // Touch mode only
private bool wasZoomingLastFrame; // Touch mode only
private Vector2[] lastZoomPositions; // Touch mode only
void Awake() {
cam = GetComponent<Camera>();
}
void Update() {
if (Input.touchSupported && Application.platform != RuntimePlatform.WebGLPlayer) {
HandleTouch();
} else {
HandleMouse();
}
}
void HandleTouch() {
switch(Input.touchCount) {
case 1: // Panning
wasZoomingLastFrame = false;
// If the touch began, capture its position and its finger ID.
// Otherwise, if the finger ID of the touch doesn't match, skip it.
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Began) {
lastPanPosition = touch.position;
panFingerId = touch.fingerId;
} else if (touch.fingerId == panFingerId && touch.phase == TouchPhase.Moved) {
PanCamera(touch.position);
}
break;
case 2: // Zooming
Vector2[] newPositions = new Vector2[]{Input.GetTouch(0).position, Input.GetTouch(1).position};
if (!wasZoomingLastFrame) {
lastZoomPositions = newPositions;
wasZoomingLastFrame = true;
} else {
// Zoom based on the distance between the new positions compared to the
// distance between the previous positions.
float newDistance = Vector2.Distance(newPositions[0], newPositions[1]);
float oldDistance = Vector2.Distance(lastZoomPositions[0], lastZoomPositions[1]);
float offset = newDistance - oldDistance;
ZoomCamera(offset, ZoomSpeedTouch);
lastZoomPositions = newPositions;
}
break;
default:
wasZoomingLastFrame = false;
break;
}
}
void HandleMouse() {
// On mouse down, capture it's position.
// Otherwise, if the mouse is still down, pan the camera.
if (Input.GetMouseButtonDown(0)) {
lastPanPosition = Input.mousePosition;
} else if (Input.GetMouseButton(0)) {
PanCamera(Input.mousePosition);
}
// Check for scrolling to zoom the camera
float scroll = Input.GetAxis("Mouse ScrollWheel");
ZoomCamera(scroll, ZoomSpeedMouse);
}
void PanCamera(Vector3 newPanPosition) {
// Determine how much to move the camera
Vector3 offset = cam.ScreenToViewportPoint(lastPanPosition - newPanPosition);
Vector3 move = new Vector3(offset.x * PanSpeed, 0, offset.y * PanSpeed);
// Perform the movement
transform.Translate(move, Space.World);
// Ensure the camera remains within bounds.
Vector3 pos = transform.position;
pos.x = Mathf.Clamp(transform.position.x, BoundsX[0], BoundsX[1]);
pos.z = Mathf.Clamp(transform.position.z, BoundsZ[0], BoundsZ[1]);
transform.position = pos;
// Cache the position
lastPanPosition = newPanPosition;
}
void ZoomCamera(float offset, float speed) {
if (offset == 0) {
return;
}
cam.fieldOfView = Mathf.Clamp(cam.fieldOfView - (offset * speed), ZoomBounds[0], ZoomBounds[1]);
}
}
The Panning and Zooming are working fine but only works when i make transform.position = pos; a comment. This line is what messes my entire panning and zooming system up. Once i make it a comment, The panning and zooming works, but without boundaries. And i need those boundaries. I'm using a terrain for my scene. that's where my entire project settles on.
What happens is when i press play on my unity editor, it all looks fine until i click on the screen. Once my mouse button touches the screen on play mode, my camera just faces an entirely different direction. The entire camera translate changes, i won't even see any of the Gameobjects on my scene anymore. Does anyone know where the problem could be coming from?

ScreenPointtoRay Creating problems for mouse follow script

I am confused as to why my game cursor follow script does not seem to perform differently based on the character's position. I want the player to press "E" if the player hovers the mouse over the character's hand and clicks and drags the arm will move up and down following the mouse position.
The script was working until I moved my character along the X axis and found that the location the mouse had to click and drag stayed at the arm's original position even as the
character, his arm, and camera moved away. Would anyone have any idea why? I've pasted in the script for finding the Mouse's position and the script for having my game object copy the mouse's position.
I uploaded some videos of the script working on YouTube as well
https://www.youtube.com/watch?v=grhnqckOfc0
https://www.youtube.com/watch?v=ZlLLgnU8yMc
Thanks for your time!
public static class GameCursor
{
public static LayerMask mask;
public static Vector2 WorldPosition
{
get
{
float distance;
int mask = 1<<9; //setting layer mask to layer 9
mask = ~mask; //setting the layer mask to ignore layer(~)
//adding in the layermask to raycast will ignore 9th layer
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(ray.origin, ray.direction * 10000f, Color.black);
if (_gamePlane.Raycast(ray, out distance))
return ray.GetPoint(distance);
return Vector2.zero;
}
}
private static Plane _gamePlane = new Plane(Vector3.forward,0);
}
public GameObject ArmR;
public static Vector2 OffsetPoint;
public Vector2 OffsetVec2;
void Start ()
{
}
private void Update()
{
if (Input.GetKey (KeyCode.E)) {
Follow ();
}
if (Input.GetKeyUp (KeyCode.E)) {
}
//print (transform.eulerAngles.z);
//Offset.transform.position = OffsetVec2;
OffsetPoint = GameCursor.WorldPosition + OffsetVec2;
Vector3 clampedRotation = transform.eulerAngles;
// Clamp the z value
if (clampedRotation.z > 90.0f) clampedRotation.z = 180.0f - clampedRotation.z;{
clampedRotation.z = Mathf.Clamp (clampedRotation.z, 0, 90);
clampedRotation.z = Mathf.Clamp (clampedRotation.z, -90, 180);
}
// assign the clamped rotation
ArmR.transform.rotation = Quaternion.Euler(clampedRotation);
//if(ArmR.transform.eulerAngles.z >= 350 || transform.eulerAngles.z <= 270){
//Debug.Log ("no");
//}
if(ArmR.transform.eulerAngles.z == 0){
//Debug.Log ("AT0");
}
if(ArmR.transform.eulerAngles.z == 90){
//Debug.Log ("AT90");
}
}
void Follow(){
ArmR.transform.up = -GameCursor.WorldPosition + OffsetVec2;
}
private void OnDrawGizmos()
{
Gizmos.DrawIcon(GameCursor.WorldPosition, "wallll", true);
}
}

Updating Texture During Movement

I'm new to this so not completely sure whether I am posting this correctly, but I have been having a few issues when creating my game. My main goal is to create a topdown shooter styled game, using movement where the 'player' rotates based on the current position of the mouse and can press 'w' to move towards it at a set speed.
The main issue is, when the game loads, the movement works exactly how I want it to, but the texture itself is not moving, but only the drawRectangle.
Game1.cs:
player = new Player(Content, #"graphics\Player1", 500, 500, spritePosition);
spritePosition = new Vector2(player.CollisionRectangle.X, player.CollisionRectangle.Y);
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
KeyboardState keyboard = Keyboard.GetState();
MouseState mouse = Mouse.GetState();
IsMouseVisible = true;
distance.X = mouse.X - spritePosition.X;
distance.Y = mouse.Y - spritePosition.Y;
//Works out the rotation depending on how far away mouse is from sprite
rotation = (float)Math.Atan2(distance.Y, distance.X);
// TODO: Add your update logic here
spritePosition = spriteVelocity + spritePosition;
spriteOrigin = new Vector2(player.DrawRectangle.X / 2, player.DrawRectangle.Y / 2);
if (Keyboard.GetState().IsKeyDown(Keys.W))
{
spriteVelocity.X = (float)Math.Cos(rotation) * tangentialVelocity;
spriteVelocity.Y = (float)Math.Sin(rotation) * tangentialVelocity;
}
else if(spriteVelocity != Vector2.Zero)
{
Vector2 i = spriteVelocity;
spriteVelocity = i -= friction * i;
}
This is the main movement code from the Update function as well as where the new player has been created.
Player.cs:
class Player
{
Texture2D sprite;
Rectangle drawRectangle;
int health = 100;
public Player(ContentManager contentManager, string spriteName, int x , int y, Vector2 velocity)
{
LoadContent(contentManager, spriteName, x, y, velocity);
}
public Rectangle CollisionRectangle
{
get { return drawRectangle; }
}
public Rectangle DrawRectangle
{
get { return drawRectangle; }
set { drawRectangle = value; }
}
public int Health
{
get { return health; }
set {
health = value;
if (health <= 0)
health = 0;
if (health > 100)
health = 100;
}
}
public Vector2 Velocity
{
get { return Velocity; }
set { Velocity = value; }
}
public void Update(GameTime gameTime, KeyboardState keyboard, MouseState mouse)
{
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(sprite, drawRectangle, Color.White);
}
private void LoadContent(ContentManager contentManager, string spriteName, int x, int y, Vector2 velocity)
{
sprite = contentManager.Load<Texture2D>(spriteName);
drawRectangle = new Rectangle(x - sprite.Width / 2, y - sprite.Height / 2, sprite.Width, sprite.Height);
}
}
I didn't know what to include in the Update function of the player.cs, whether the code for movement should go in there or the main Game1.cs.
Hopefully this is enough code for you guys to be able to help. Sorry for there being quite a lot of code, but I'm just unsure where the error is occurring.
Thanks in advance
For the rotation you would want to use 'another' kind of spriteBatch.Draw, because the draw function can have more parameters than your currently using.
The full draw function is as followed:
SpriteBatch.Draw(Texture2D texture, Vector2 position, Rectangle sourceRectangle, Color color, float rotation, Vector2 origin, float scale, SpriteEffects effects, float layerdepht)
As you can see, now we have a parameter for rotation that can be used.
So your code will look something like this:
spriteBatch.Draw(sprite, drawRectangle, null, Color.White, rotation, Vector2.Zero, 1, SpriteEffects.None, 0);
As for your question for where your code should go. It is good to learn yourself to put the code where it belongs, in this case the player. Because when your programs become bigger, it would be very messy to do it this way.
To call the update function in your player class, you can just simply call player.Update(gameTime, keyboard, mouse) in the Update of Game1.

Unable to create collision rectangle

I am trying to make a small game for my programming class at college and I am having a problem trying to create a rectangle for collision.
When I try and use the width and height from my texture. I get an error telling me that I can't convert from a float to an int. But the pixel size of the image is not a float value?
Here is the code I have in my game objects class (there is a lot of comments to help direct where things are meant to go):
class ButtonSprite
{
public Texture2D Art;
public Vector2 Position;
public ButtonSprite(Vector2 pos, Texture2D tex)
{
// Copy the texture "tex" into the "Art" class variable
Art = tex;
// Copy the vector "pos" into the "Position" class variable
Position = pos;
}
public void DrawMe(SpriteBatch sb, Color col)
{
// use the spritebatch "sb" to draw the sprite at "Position" using the texture "Art" with the tint from "col"
sb.Draw(Art, Position, col);
}
}
class PlayerSprite
{
public Texture2D Art;
public Vector2 Position;
public Rectangle CollisionRect;
public PlayerSprite(Vector2 pos, Texture2D tex)
{
// Copy the texture "tex" into the "Art" class variable
Art = tex;
// Copy the vector "pos" into the "Position" class variable
Position = pos;
// create a new CollisionRect Rectangle using the X and Y from Position and the Width and Height from Art
CollisionRect = new Rectangle(Position.X, Position.Y, Art.Width, Art.Height);
}
public void UpdateMe(ButtonState leftB, ButtonState rightB, ButtonState downB, ButtonState upB)
{
// if leftB is pressed
if (leftB == ButtonState.Pressed)
{
// subtract 1 from the X that belongs to Position
Position.X -= 1;
}
// endif
// if rightB is pressed
if (rightB == ButtonState.Pressed)
{
// add 1 to the X that belongs to Position
Position.X += 1;
}
// endif
// if downB is pressed
if (downB == ButtonState.Pressed)
{
// add 1 to the Y that belongs to Position
Position.Y += 1;
}
// endif
// if upB is pressed
if (upB == ButtonState.Pressed)
{
// subtract 1 from the Y that belongs to Position
Position.Y -= 1;
}
// endif
// set the X that belongs to CollisionRect to equal the integer version of the X that belongs to Position
// set the Y that belongs to CollisionRect to equal the integer version of the Y that belongs to Position
}
public void DrawMe(SpriteBatch sb)
{
// use the spritebatch "sb" to draw the sprite at "Position" using the texture "Art" with a white tint
sb.Draw(Art, Position, Color.White);
}
}
}
Right off the bat, I would suggest you calculate your collisions using the movement too. This will prevent more glitches (e.g. passing through walls).
A good way to do this is to inflate the target rectangle (temporarily) by the size of the moving rectangle. Then, you perform a line to bounding box intersection. This will give you an intersection point, while being safer against glitches.
Try this line when building your collision rect. It will convert the height & width floats to integers. The + 1 is optional.
CollisionRect = new Rectangle(Position.X, Position.Y, (int)Art.Width + 1, (int)Art.Height + 1);

Having problems drawing animations in monogame

I am trying to create a spaceship with multiple animations (idle, attack, damaged, etc)
But when I'm trying to change the animations I see the first frame of the current animation for a split second on the "old" position (where the animation was changed the last time)
Picture for explanation: http://i.imgur.com/L3O8rsc.png
The red rectangle is supposed to be a health bar.
The class that runs my animations:
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace Test
{
class Animation
{
Texture2D spriteStrip;
float scale;
int elapsedTime;
int frameTime;
int frameCount;
int currentFrame;
Color color;
// The area of the image strip we want to display
Rectangle sourceRect = new Rectangle();
// The area where we want to display the image strip in the game
Rectangle destinationRect = new Rectangle();
public int FrameWidth;
public int FrameHeight;
public bool Active;
public bool Looping;
public Vector2 Position;
public void Initialize(Texture2D texture, Vector2 position, int frameWidth, int frameHeight, int frameCount, int frametime, Color color, float scale, bool looping)
{
this.color = color;
this.FrameWidth = frameWidth;
this.FrameHeight = frameHeight;
this.frameCount = frameCount;
this.frameTime = frametime;
this.scale = scale;
Looping = looping;
Position = position;
spriteStrip = texture;
elapsedTime = 0;
currentFrame = 0;
Active = true;
}
public void Update(GameTime gameTime)
{
if (Active == false) return;
elapsedTime += (int)gameTime.ElapsedGameTime.TotalMilliseconds;
if (elapsedTime > frameTime)
{
currentFrame++;
if (currentFrame == frameCount)
{
currentFrame = 0;
if (Looping == false)
Active = false;
}
elapsedTime = 0;
}
sourceRect = new Rectangle(currentFrame * FrameWidth, 0, FrameWidth, FrameHeight);
destinationRect = new Rectangle((int)Position.X - (int)(FrameWidth * scale) / 2, (int)Position.Y - (int)(FrameHeight * scale) / 2, (int)(FrameWidth * scale), (int)(FrameHeight * scale));
}
public void Draw(SpriteBatch spriteBatch)
{
if (Active)
{
spriteBatch.Draw(spriteStrip, destinationRect, sourceRect, color);
}
}
}
}
The reason that I wrote the whole code is because I don't know where the problem is.
In my Game1.cs class I have:
Global Variables:
Texture2D playerTexture;
Texture2D playerShootingTexure;
Animation playerAnimation = new Animation();
Animation ShootingAnimation = new Animation();
...
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
playerTexture = Content.Load<Texture2D>("Graphics/Player/PlayerShip");
playerShootingTexure = Content.Load<Texture2D>("Graphics/Player/Player_Shooting");
playerAnimation.Initialize(playerTexture, Vector2.Zero, playerTexture.Width / 5, playerTexture.Height, 5, 50, Color.Wheat, 1f, true);
ShootingAnimation.Initialize(playerShootingTexure, Vector2.Zero, playerShootingTexure.Width / 5, playerShootingTexure.Height, 5, 50, Color.WhiteSmoke, 0.75f, true);
}
Where I change the animations:
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// Start drawing
spriteBatch.Begin();
if (Player_Attacking == false)
{
player.PlayerAnimation = playerAnimation;
}
else
{
player.PlayerAnimation = ShootingAnimation;
}
player.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
Note: Player_Attacking is a boolean variable. When 'Space' is pressed, the value of the variable changes to TRUE, when 'Space' is released, value is FALSE
Please help!
Thanks in advance!
And sorry for huge wall of text
I'm a little unclear on the exact issue, so maybe you can help clarify if I'm not understanding.
But based on your picture, it seems when you press space to fire, the player animation should change to light up his gun with blue flames (or w/e it is :)) And it looks like it is doing that, but it's in the wrong position (above the health bar - I see the laser it is shooting is in the right location :))
But then it corrects itself once the shooting is done, as shown by the second picture (no more blue flames).
So this implies the Animation for the Player Shooting is using the wrong position.
Are you:
Updating your Player Shooting Animation's Position in your Player Update?
Calling your Player Shooting Animation's Update in your Player Update?
so you should have this somewhere in your Player Update
PlayerAnimation.Position = Position;
PlayerAnimation.Update(gameTime);
Also, try moving the check for which Player Animation to use in the Update of your Game1.cs:
protected override void Update(GameTime gameTime)
{
if (Player_Attacking == false)
{
player.PlayerAnimation = playerAnimation;
}
else
{
player.PlayerAnimation = ShootingAnimation;
}
player.Update(gameTime);
}

Categories

Resources