使用XNA使Texture2D朝着鼠标点击的方向移动
本文关键字:方向 移动 鼠标 XNA Texture2D 使用 | 更新日期: 2023-09-27 18:17:57
这是我到目前为止的代码。我试着让子弹朝着点击鼠标的方向移动。我有一个子弹矩形和一个Texture2D,同样的也适用于炮弹发射的地方。
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);
}
}
}
下面是一些关于如何处理子弹相对于点的速度和方向的伪代码。
// 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;
对于像大炮这样的静态实体,将"player"替换为"cannon",将"mouseClick"替换为"player"。
(我从记忆中回忆Sin
和Cos
的位置,所以如果这是错误的设置,希望有人能纠正我。)