【发布时间】:2015-05-02 00:51:08
【问题描述】:
我正在使用 C# XNA 4.0 制作游戏,我希望游戏中的枪可以旋转以面对玩家并向他们射击。我在下面附上了一张图片来总结这一点。
我已经实现了射击 AI,但我想知道如何让枪旋转以使其面向玩家。 player 类使用 Vector2 来表示它的位置,而 gun 类有一个浮点值来表示它的旋转,那么如何让枪旋转指向向量呢? (我很确定我知道如何绘制旋转的枪,我只需要知道如何改变枪的旋转。)
编辑:
这是我的枪类的全部。构造函数获取一个位置(它将被放置在关卡中的位置)、一个射速(它每秒发射多少次)和一个子弹速度(子弹移动的速度)。有一个单独的子弹类,但这对于解释枪类是不必要的。
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课程吗? -
是的。枪类已发布。
-
@MickyDuncan - OP 正在执行
bullets.ToList(),因为他正在循环内执行bullets.Remove(bullet)。所以 OP 需要做类似for (var i = bullets.Count - 1; i >= 0; i--)的事情,然后是bullets.RemoveAt(i); -
@dbc 好地方,我的坏。