This is the code I have so far. I'm trying to get the bullet to move in the direction of where the mouse is clicked. I have a bullet Rectangle, and a Texture2D, and the same goes for the cannon from where the bullet is fired.
namespace Targeted
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
int screenWidth;
int screenHeight;
int speedX;
int speedY;
MouseState oldMouse;
Texture2D cannon;
Rectangle cannonRect;
Texture2D bullet;
Rectangle bulletRect;
KeyboardState kb;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
screenWidth = graphics.GraphicsDevice.Viewport.Width;
screenHeight = graphics.GraphicsDevice.Viewport.Height;
oldMouse = Mouse.GetState();
speedX = 0;
speedY = 0;
cannonRect = new Rectangle((screenWidth / 2) - 100, (screenHeight / 2) - 100, 100, 100);
bulletRect = new Rectangle(cannonRect.X, cannonRect.Y, 10, 10);
this.IsMouseVisible = true;
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
cannon = Content.Load<Texture2D>("Smoothed Octagon");
bullet = Content.Load<Texture2D>("White Square");
// TODO: use this.Content to load your game content here
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
bulletRect.X += speedX;
bulletRect.Y += speedY;
this.IsMouseVisible = true;
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || kb.IsKeyDown(Keys.Escape))
this.Exit();
// TODO: Add your update logic here
MouseState mouse = Mouse.GetState();
kb = Keyboard.GetState();
if (mouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released)
{
bulletRect.X += speedX;
bulletRect.Y += speedY;
}
oldMouse = mouse;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.Draw(bullet, bulletRect, Color.White);
spriteBatch.Draw(cannon, cannonRect, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
Here's some pseudocode of how to handle bullet velocity and orientation relative to a point.
// On MouseClick
float angle = Math.Atan2(mouseClick.X - player.X, mouseClick.Y - player.Y);
bulletVelocity.X = (Math.Cos(angle) + Math.Sin(angle)) * bulletSpeed;
bulletVelocity.Y = (-Math.Sin(angle) + Math.Cos(angle)) * bulletSpeed;
// On Update Positions
bullet.X += bulletVelocity.X;
bullet.Y += bulletVelocity.Y;
For static entities like cannons, replace "player" with "cannon" and "mouseClick" with "player".
(I'm recalling the positions of Sin
and Cos
from memory, so hopefully someone can correct me if that's the wrong setup.)