XNA - 我怎样才能提高我的精灵速度

时间:2014-04-07 16:58:14

标签: c# xna game-physics

所以我是编程的初学者,我需要帮助我如何让我的精灵速度提高(添加冲刺功能)

我已经尝试过自己,但我失败了,如果有人能解释我怎么做,我会非常感激。

我想做的就是如果我按下我的Xbox控制器上的右触发器,同时移动我的左拇指杆,将速度从4改为6。

这是我尝试过的东西,我意识到这不起作用,因为当我按下触发器时它会让精灵移动。

if (pad1.Triggers.Right < 0.0f)
  position += new Vector2(-6, 0);

if (pad1.Triggers.Right >= 0.4f)
  position += new Vector2(6, 0);

我没有选择,所以有人请帮忙。

2 个答案:

答案 0 :(得分:1)

这基本上是一个物理问题。向位置添加恒定量只会更多地移动精灵。您可能正在寻找的是一种在短时间内提高速度的方法,这种方式称为加速度。

const float AccelerationForce = 0.ff;
const float MaxAccelerationForce = 0.8f;;
static readonly Vector2 MaxAcceleration
    = new Vector2(MaxAccelerationForce, MaxAccelerationForce);
static readonly Vector2 Acceleration = new Vector2(AccelerationForce, 0);
static readonly Vector2 Deceleration = new Vector2(-AccelerationForce, 0);
Vector _currentAcceleration = new Vector2(0, 0);
Vector _currentVelocity = new Vector2(0, 0);

Vector2 Clamp(Vector2 value, Vector2 min, Vector2 max)
{
    var x = MathHelper.Clamp(value.X, min.X, max.X);
    var y = MathHelper.Clamp(value.Y, min.Y, max.Y);

    return new Vector2(x, y);
}

bool RequiresAcceleration(float currentForce)
{
    return currentForce >= AccelerationForce;
}

var currentForce = GetCurrentForce();
// Calculate whether we need to accelerate or decelerated
var acceleration = RequiresAcceleration(currentForce)
                       ? Acceleration
                       : Deceleration;
var newAcceleration = _currentAcceleration + acceleration;
// acceleration is bounded MaxAcceleration > _currentAcceleration > 0
_currentAcceleration = Clamp(newAcceleration, Vector2.Zero, MaxAcceleration);

_currentVelocity += _currentAcceleration;

// Code to move the player

if (pad1.Triggers.Right < 0.0f)
  position += _currentVelocity);

if (pad1.Triggers.Right >= 0.4f)
  position -= _currentVelocity;

答案 1 :(得分:0)

我相信这正是你想要实现的目标。编辑帖子也很容易,请编辑帖子而不是评论更新。

        if (pad1.Triggers.Right < 0)
            // This checks if left thumbstick is less than 0.
            // If it is less than zero it sets position.X += -6. 
            // If it is not less then it sets position.X += -4.
            position.X -= (pad1.ThumbSticks.Left.X < 0) ? 6 : 4;
        else if (pad1.Triggers.Right >= 0.4f) // shouldn't this be > 0.0f or > 0 ?
            // This is the same as above just in the right direction.
            position.X += (pad1.ThumbSticks.Left.X > 0) ? 6 : 4;