Display vector co-ordinates as String values [closed] - c#

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)

Related

Bullet doens't move. Unity

I am working on a 2D, topdown, roguelike game but i got stuck when i tried to make a shooting system.
when i run it and press the arrow keys, the bullet spawns and points in the right direction. It juste doesn't move in any way.
This is my code and i hope someone can figure it out. Btw, everything is connected. The player and the bullet prefab.
using System.Collections;
using System.Linq;
using UnityEngine;
namespace Assets.Scripts
{
[RequireComponent(typeof(Player))]
public class PlayerShootController : ShootControllerBase
{
[SerializeField]
private int _numberOfBombs;
public int NumberofBombs
{
get { return _numberOfBombs; }
set { _numberOfBombs = value; }
}
[SerializeField]
private PlayerHeadController _headObject;
public PlayerHeadController HeadObject
{
get { return _headObject; }
set { _headObject = value; }
}
[SerializeField]
private Bomb _bombPrefab;
public Bomb BombPrefab
{
get { return _bombPrefab; }
set { _bombPrefab = value; }
}
public bool IsShooting { get; private set; }
private KeyCode _shootKey;
private Vector2 _shootDirection;
private Player _player;
public override void Start()
{
base.Start();
_player = GetComponent<Player>();
}
public override void Update()
{
base.Update();
if (IsShooting)
{
SetHeadDirection(_shootKey);
return;
}
if (InputHelpers.IsAnyKey(KeyCode.UpArrow, KeyCode.DownArrow, KeyCode.LeftArrow, KeyCode.RightArrow))
{
if (Input.GetKey(KeyCode.UpArrow))
{
_shootDirection = new Vector2(0, BulletSpeed);
_shootKey = KeyCode.UpArrow;
}
else if (Input.GetKey(KeyCode.DownArrow))
{
_shootDirection = new Vector2(0, -BulletSpeed);
_shootKey = KeyCode.DownArrow;
}
else if (Input.GetKey(KeyCode.LeftArrow))
{
_shootDirection = new Vector2(-BulletSpeed, 0);
_shootKey = KeyCode.LeftArrow;
}
else if (Input.GetKey(KeyCode.RightArrow))
{
_shootDirection = new Vector2(BulletSpeed, 0);
_shootKey = KeyCode.RightArrow;
}
StartCoroutine(Shoot());
}
if (NumberofBombs > 0 && InputHelpers.IsAnyKeyDown(KeyCode.LeftShift, KeyCode.RightShift, KeyCode.E))
{
var bomb = (Bomb) Instantiate(BombPrefab);
bomb.transform.position = transform.position;
NumberofBombs--;
}
}
IEnumerator Shoot()
{
IsShooting = true;
while (Input.GetKey(_shootKey))
{
var bullet = (Rigidbody2D)Instantiate(BulletPrefab);
bullet.GetComponent<BulletScript>().Shooter = transform.gameObject;
bullet.transform.position = transform.position;
if (_shootDirection.y > 0)
{
bullet.transform.Rotate(0, 0, -90);
}
else if (_shootDirection.y < 0)
{
bullet.transform.Rotate(0, 0, 90);
}
else if (_shootDirection.x > 0)
{
TransformHelpers.FlipX(bullet.gameObject);
}
bullet.AddForce(_shootDirection);
bullet.AddForce(_player.GetComponent<Rigidbody2D>().GetPointVelocity(_player.transform.position) * 0.02f);
if (ShootClips.Any())
{
var clipToPlay = ShootClips[Random.Range(0, ShootClips.Count)];
clipToPlay.pitch = Random.Range(MinShootPitch, MaxShootPitch);
clipToPlay.Play();
}
yield return new WaitForSeconds(ShootingSpeed);
}
IsShooting = false;
//Reset head flipping
if (_headObject.transform.localScale.x < 0)
{
TransformHelpers.FlipX(_headObject.gameObject);
}
}
private void SetHeadDirection(KeyCode shootKey)
{
switch (shootKey)
{
case KeyCode.UpArrow:
_headObject.SetHeadDirection(PlayerHeadController.HeadDirection.Up);
break;
case KeyCode.DownArrow:
_headObject.SetHeadDirection(PlayerHeadController.HeadDirection.Down);
break;
case KeyCode.LeftArrow:
_headObject.SetHeadDirection(PlayerHeadController.HeadDirection.Left);
break;
case KeyCode.RightArrow:
_headObject.SetHeadDirection(PlayerHeadController.HeadDirection.Right);
break;
}
}
}
}
try this:
bullet.AddForce(_shootDirection*moveSpeed*Time.deltaTime);
instead of this:
bullet.AddForce(_shootDirection);
bullet.AddForce(_player.GetComponent<Rigidbody2D>().GetPointVelocity(_player.transform.position) * 0.02f);
tweak the speed for desired result, and if you want the bullet to follow the player you will need to update the shoot direction every certain time with a couroutine

How can I change image fillamount direction?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class loadingcolorful : MonoBehaviour
{
public float speed = 0.0f;
public bool fillAmount = false;
public bool rotate = false;
public bool changeRotationDir = false;
public bool changeFillDir = false;
private RectTransform rectTransform;
private Image imageComp;
// Use this for initialization
void Start()
{
imageComp = GetComponent<RectTransform>().GetComponent<Image>();
rectTransform = transform.parent.gameObject.transform.GetComponent<RectTransform>();
}
// Update is called once per frame
void Update()
{
if (fillAmount == true)
{
if (imageComp.fillAmount != 1f)
{
if (changeFillDir == true)
{
imageComp.fillAmount -= speed;
}
else
{
imageComp.fillAmount += speed;
}
}
else
{
imageComp.fillAmount = 0f;
}
}
else
{
if (imageComp.fillAmount == 0f)
{
imageComp.fillAmount = 0f;
}
else
{
imageComp.fillAmount = 1f;
}
}
if (rotate == true)
{
if (changeRotationDir == true)
{
rectTransform.Rotate(new Vector3(0, 0, -1));
}
else
{
rectTransform.Rotate(new Vector3(0, 0, 1));
}
}
}
}
The problem is at this place :
if (changeFillDir == true)
{
imageComp.fillAmount -= speed;
}
When it will get to 0 it will not continue to fill the image to the other direction just the image will stay empty. My guess is that the values of the FillAmount ragne is between 1 and 0.
Is there a way to make it happen ?
It's a bit of a hack, but you can switch to a negative scale value and start increasing the fillAmout again. This will make it fill in the other direction, taking the 0 point as pivot.
Assuming you are filling horizontally, flipping the scale would look something like this:
transform.localScale = new Vector3(-1, 1, 1);
A working solution like I wanted :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class loadingcolorful : MonoBehaviour
{
public float speed = 0.0f;
public bool fillAmount = false;
public bool rotate = false;
public bool changeRotationDir = false;
public bool changeFillDir = false;
public bool useBackGroundImage = true;
private RectTransform rectTransform;
private Image imageComp;
private Image backGroundImage;
// Use this for initialization
void Start()
{
imageComp = GetComponent<RectTransform>().GetComponent<Image>();
backGroundImage = transform.parent.gameObject.transform.GetComponent<Image>();
UseBackgImage();
}
// Update is called once per frame
void Update()
{
UseBackgImage(useBackGroundImage);
if (fillAmount == true)
{
if (imageComp.fillAmount != 1f)
{
if (changeFillDir == true)
{
if (imageComp.fillAmount == 0)
{
imageComp.fillAmount = 1f;
}
imageComp.fillAmount -= speed;
}
else
{
imageComp.fillAmount += speed;
}
}
else
{
imageComp.fillAmount = 0f;
}
}
else
{
if (imageComp.fillAmount == 0f)
{
imageComp.fillAmount = 0f;
}
else
{
imageComp.fillAmount = 1f;
}
}
if (rotate == true)
{
if (changeRotationDir == true)
{
rectTransform.Rotate(new Vector3(0, 0, -1));
}
else
{
rectTransform.Rotate(new Vector3(0, 0, 1));
}
}
}
private void UseBackgImage()
{
if (useBackGroundImage == true)
{
backGroundImage.enabled = true;
rectTransform = transform.parent.gameObject.transform.GetComponent<RectTransform>();
}
else
{
backGroundImage.enabled = false;
rectTransform = transform.GetComponent<RectTransform>();
}
}
private void UseBackgImage(bool UseBackGroundImage)
{
if (useBackGroundImage == true)
{
backGroundImage.enabled = true;
}
else
{
backGroundImage.enabled = false;
}
}
}

Monogame multiple objects same animation

as the titel say's I'm trying to make a game in Monogame, a Bomberman clone, but atm when I try to spawn more then one bomb the animation just moves to the new location. The game object stays where it is supposed to, but it does not have the animation. I think the problem is that it loads the same animation which has been loaded but I just cant seem to figure out how to get it to spawn a new animation everytime a bomb spawns.
I use Content.Load to get the sorite animation, and spawn the bomb with a clone() function with the animation.
var bombAni = new Dictionary<string, Animation>() {
{"Bomb", new Animation(Content.Load<Texture2D>("Obstacle/Bomb"), 3) },
};
_sprites = new List<Sprite>() {
new Player(animations) {
_bomb = new Bomb(bombAni),
Position = new Vector2(32, 32),
Input = new Input() {
Up = Keys.W,
Down = Keys.S,
Left = Keys.A,
Right = Keys.D,
Space = Keys.Space,
}
}
};
public void Play(Animation animation) {
if (animation == _animation) {
return;
}
_animation = animation;
_animation.CurFrame = 0;
_timer = 0;
}
private void AddBomb(List<Sprite> sprites) {
var bomb = _bomb.Clone() as Bomb;
switch (_direction) {
case "Up":
bomb.Position = _position + new Vector2(0, -32);
break;
case "Down":
bomb.Position = _position + new Vector2(0, 32);
break;
case "Left":
bomb.Position = _position + new Vector2(-32, 0);
break;
case "Right":
bomb.Position = _position + new Vector2(32, 0);
break;
}
bomb.lifeSpan = 3f;
bomb.Parent = this;
bombCount++;
sprites.Add(bomb);
}
public Sprite(Dictionary<string, Animation> animations) {
_animations = animations;
_animationManager = new AnimationManager(_animations.First().Value);
}
namespace CompetenceWeek.scripts {
public class Bomb : Sprite {
public float lifeSpan;
private float _timer;
public Bomb(Dictionary<string, Animation> animations) : base(animations) {
}
public Bomb(Texture2D texture) : base(texture) {
}
public override void Update(GameTime gameTime, List<Sprite> sprites) {
_timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
SetAnimations();
_animationManager.Update(gameTime);
if (_timer > lifeSpan) {
isDead = true;
}
}
}
}
namespace CompetenceWeek.scripts {
public class Sprite : ICloneable {
protected AnimationManager _animationManager;
protected Dictionary<string, Animation> _animations;
protected Vector2 _position;
protected Texture2D _texture;
public bool Walkable { get; set; } = false;
public bool isDead = false;
public Player Parent { get; set; }
public Input Input;
public Vector2 Position {
get { return _position; }
set {
_position = value;
if(_animationManager != null) {
_animationManager.Posistion = _position;
}
}
}
public float Speed = 2.5f;
public Vector2 Velocity;
public virtual void Draw(SpriteBatch spriteBatch) {
if(_texture != null) {
spriteBatch.Draw(_texture, Position, Color.White);
} else if (_animationManager != null) {
_animationManager.Draw(spriteBatch);
} else {
throw new Exception("somthings not right");
}
}
public Sprite(Dictionary<string, Animation> animations) {
_animations = animations;
_animationManager = new AnimationManager(_animations.First().Value);
}
public Sprite(Texture2D texture) {
_texture = texture;
}
public virtual void Update(GameTime gameTime, List<Sprite> sprites) {
SetAnimations();
_animationManager.Update(gameTime);
Position += Velocity;
Velocity = Vector2.Zero;
}
protected virtual void SetAnimations() {
if (Velocity.X > 0) {
_animationManager.Play(_animations["PlayerRight"]);
} else if (Velocity.X < 0) {
_animationManager.Play(_animations["PlayerLeft"]);
} else if (Velocity.Y > 0) {
_animationManager.Play(_animations["PlayerDown"]);
} else if (Velocity.Y < 0) {
_animationManager.Play(_animations["PlayerUp"]);
}
}
public object Clone() {
return this.MemberwiseClone();
}
}
}
The problem is with this segment:
protected Dictionary<string, Animation> _animations;
public object Clone() {
return this.MemberwiseClone();
}
When you perform a memberwise clone, it creates a shallow copy, reusing existing references to reference-type objects. This means that the Clone will share the same animation state with the original object.
The solution to this, is to instantiate a new copy of all of the Animations every time you want to clone Bomb.
Something like this:
public object Clone() {
var bomb = (Bomb)this.MemberwiseClone();
bomb.InitAnimations(new Dictionary<string, Animation>() {
{"Bomb", new Animation(Content.Load<Texture2D>("Obstacle/Bomb"), 3) },
};
return bomb;
}

C# XNA Collision Detection with list of objects

I am currently learning C# and XNA and I am having some troubles with getting my collision detection to work properly. I wish for my player to disappear when the Enemy object intersects.
Below shows my code within the Obj class
class Obj
{
public Vector2 position;
public float rotation = 0.0f;
public Texture2D spriteIndex;
public string spriteName;
public float speed = 0.0f;
public float scale = 1.0f;
public bool alive = true;
public Rectangle area;
public bool solid = false;
public Obj(Vector2 pos)
{
position = pos;
}
private Obj()
{
}
public virtual void Update()
{
if (!alive) return;
UpdateArea();
pushTo(speed, rotation);
}
public virtual void LoadContent(ContentManager content)
{
spriteIndex = content.Load<Texture2D>("sprites\\" + spriteName);
area = new Rectangle(0, 0, spriteIndex.Width, spriteIndex.Height);
}
public virtual void Draw(SpriteBatch spriteBatch)
{
if (!alive) return;
Rectangle Size;
Vector2 center = new Vector2(spriteIndex.Width / 2, spriteIndex.Height / 2);
spriteBatch.Draw(spriteIndex, position, null, Color.White, MathHelper.ToRadians(rotation), center, scale, SpriteEffects.None, 0);
}
public bool Collision(Vector2 pos, Obj obj)
{
Rectangle newArea = new Rectangle(area.X, area.Y, area.Width, area.Height);
newArea.X += (int)pos.X;
newArea.Y += (int)pos.Y;
foreach (Obj o in Items.objList)
{
if (o.GetType() == obj.GetType() && o.solid)
if (o.area.Intersects(newArea))
return true;
}
return false;
}
public Obj Collision(Obj obj)
{
foreach (Obj o in Items.objList)
{
if (o.GetType() == obj.GetType())
if (o.area.Intersects(area))
return o;
}
return new Obj();
}
public void UpdateArea()
{
area.X = (int)position.X - (spriteIndex.Width / 2);
area.Y = (int)position.Y - (spriteIndex.Height / 2);
}
public T CheckCollisionAgainst<T>() where T : Obj
{
// If collision detected, returns the colliding object; otherwise null.
return Items.objList
.OfType<T>()
.FirstOrDefault(o => o.solid && o.area.Intersects(area));
}
public virtual void pushTo(float pix, float dir)
{
float newX = (float)Math.Cos(MathHelper.ToRadians(dir));
float newY = (float)Math.Sin(MathHelper.ToRadians(dir));
position.X += pix * (float)newX;
position.Y += pix * (float)newY;
}
}
I am cycling through each Item in my objList to see if they intersect with each other, in this case, I want my Player to disappear if the Enemy intersects with them but this is not happening.
This code is from my Player class
class Player : Obj
{
KeyboardState keyboard;
KeyboardState prevKeyboard;
float spd;
public static Player player;
public Player(Vector2 pos)
: base(pos)
{
position = pos;
spd = 4;
spriteName = "WhiteBall";
solid = false;
player = this;
}
public override void Update()
{
player = this;
//If the player is NOT alive, end.
if (!alive) return;
keyboard = Keyboard.GetState();
//Keyboard controls for game
if(keyboard.IsKeyDown(Keys.W) && !Collision(new Vector2(0, -spd), new Enemy(new Vector2(0, 0))))
{
position.Y -= spd;
}
if (keyboard.IsKeyDown(Keys.A) && !Collision(new Vector2(-spd, 0), new Enemy(new Vector2(0, 0))))
{
position.X -= spd;
}
if (keyboard.IsKeyDown(Keys.S) && !Collision(new Vector2(0, spd), new Enemy(new Vector2(0, 0))))
{
position.Y += spd;
}
if (keyboard.IsKeyDown(Keys.D) && !Collision(new Vector2(spd, 0), new Enemy(new Vector2(0, 0))))
{
position.X += spd;
}
prevKeyboard = keyboard;
//Collision with enemy
Enemy enemy = CheckCollisionAgainst<Enemy>();
if (enemy != null)
{
alive = false;
}
base.Update();
}
public override void Draw(SpriteBatch spriteBatch)
{
spriteBatch.DrawString(Game1.font, "Pick Up The Crew", new Vector2(350, 0), Color.White);
base.Draw(spriteBatch);
}
}
If it intersects with the Enemy, it should disappear but this doesnt seem to be happening.
Based on the comments you provided, I'm taking a shot here and providing a possible solution (ensure UpdateArea is called before calling this):
public T CheckCollisionAgainst<T>() where T : Obj
{
// If collision detected, returns the colliding object; otherwise null.
return Items.objList
.OfType<T>()
.FirstOrDefault(o => o.area.Intersects(area));
}
Enemy enemy = CheckCollisionAgainst<Enemy>();
if (enemy != null)
{
alive = false;
}

Why won't my sprite draw? (XNA)

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

Categories

Resources