c# - 使用 XNA game studio 在 2D 游戏中按下按键进行射击

标签 c# xna xna-4.0

我正在使用 XNA game studio 4.0 开发一款 2D 游戏,我需要让我的“英雄” Sprite 射击一个射击 Sprite ,它是一个矩形。

当我按下左控制键进行射击时,射击是从我的玩家开始的。到目前为止,一切都还好,但问题是它永远不会停止——它的位置永远不会到达theVoid

这是我的拍摄代码:

protected override void Update(GameTime gameTime)
{
    if (Keyboard.GetState().IsKeyDown(Keys.LeftControl) && isShotted == false)
    {
        isShotted = true;
        shotPosition = playerPosition;            
    }
    if (isShotted == true && (shotPosition.X <= shotPosition.X+150) )
    {
        shotPosition.X += shotSpeed.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
    }
    else 
    { 
        isShotted = false;
        shotPosition = theVoid;
    }
}

一些说明:

  • playerPosition 是我的“英雄” Sprite 位置。
  • theVoidVector2 (700,700),当我设置 shotPosition = theVoid 时,镜头消失。

最佳答案

镜头永远不会消失,因为您每次更新都会更新 shotPosition.x。您正在检查:

if (isShotted == true && (shotPosition.X <= shotPosition.X+150) )

然后在该if内增加shotPosition.X:

shotPosition.X += shotSpeed.X * (float)gameTime.ElapsedGameTime.TotalSeconds;

解决此问题的一个选项是根据@jonhopkins 评论检查 shotPosition.X 与玩家位置。如果玩家可以以接近与射击相同的速度移动,他们可以跟随它,然后射击永远不会消失,这可能是也可能不是您想要的。

您的另一个选择是存储射击的位置,并进行比较,例如:

if (isShotted == true && (shotPosition.initialX+150 >= shotPosition.currentX) )

请确保您从玩家和对象如何围绕坐标系移动的角度来考虑这一点。如果你的玩家在 x 轴上始终保持静止,那么与他们可以在屏幕上运行相比,事情可以简化。

关于c# - 使用 XNA game studio 在 2D 游戏中按下按键进行射击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13956112/

相关文章:

C# 字典反序列化

c# - 如何在内容中实现文本文件 (XNA)

c# - 轨道力学

c# - ITextSharp : Text not wrapping around image within cell

c# - 无效的变体崩溃

c# - 使用鼠标滚轮 XNA 缩放图像

visual-studio-2010 - XNA 4.0 Visual Studio 2010错误

c# - 使用箭头键而不是拇指摇杆移动播放器

c# - C#中数组索引的类型?

c# - 如何使用 iTextsharp 在服务器映射路径上保存 pdf