I'm making a game in C# XNA 4.0 and I want the game to have guns that rotate to face the player and shoot at them. I have attached a picture below to summarise this.
I have the shooting AI implemented, but I want to know how I can make the gun rotate so that it faces the player. The player class uses a Vector2 to represent its position and the gun class has a float value to represent its rotation, so how do I make the gun rotate to point toward the vector? (I'm pretty sure I know how to draw the rotated gun, I just need to know how to alter the gun's rotation.)
Edit:
This is my Gun class in its entirety. The constructor takes a position (where it will be placed in the level), a fire rate (how many times it fires every second or so) and a bullet speed (how fast the bullets travel). There is a seperate bullet class, but that should not be necessary for explaining the gun class.
Vector2 m_position;
decimal m_fireRate;
decimal timer;
double m_bulletSpeed;
double rotation;
List<Bullet> bullets;
public Gun(Vector2 position, decimal fireRate, double bulletSpeed)
{
m_position = position;
m_fireRate = fireRate;
timer = 0.0m;
m_bulletSpeed = bulletSpeed;
bullets = new List<Bullet>();
rotation = 0.0;
}
public void Update()
{
timer += 0.025m;
if (timer % m_fireRate == 0)
{
//Create a new bullet based on the rate of fire (Obtain the gun texture from the main game class)
bullets.Add(new Bullet(m_bulletSpeed, rotation, new Vector2(m_position.X + (MyGame.GunTex.Width / 3), m_position.Y + MyGame.GunTex.Height)));
}
foreach (Bullet bullet in bullets.ToList())
{
bullet.Update();
//Delete the bullet if it is offscreen
if (bullet.Position.X >= MyGame.WindowWidth || bullet.Position.X <= 0 || bullet.Position.Y >= MyGame.WindowHeight)
{
bullets.Remove(bullet);
}
}
//ROTATE TO FOLLOW PLAYER POSITION
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(MyGame.GunTex, m_position, Color.White);
foreach(Bullet bullet in bullets)
{
bullet.Draw(spriteBatch);
}
}
Gun
class? – MickyDbullets.ToList()
because he's doingbullets.Remove(bullet)
inside the loop. So OP would need to do something likefor (var i = bullets.Count - 1; i >= 0; i--)
and then laterbullets.RemoveAt(i);
– dbc