我正在尝试在 2d Unity (C#( 中创建一种具有能量条的冲刺能力,因此它不能无休止地使用。我错过了什么?
我尝试使冲刺成为一个函数,并在按下 X 键时调用它。试图增加它的位置,但我在短距离内获得了闪烁能力。
\ this is my movement script, other variables we're declared earlier in the code
void Update() {
Vector2 mi = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
mv = mi.normalized * speed;
}
private void FixedUpdate() {
rb.MovePosition(rb.position + mv * Time.fixedDeltaTime);
}
我希望代码在按下 X 键时使玩家的速度是正常速度的两倍,但只有在能量没有耗尽时才可以使用。
看不到您对"能量"的实现,但我只会使用
public float energy;
// How much is energy reduced per second?
public float decreaseSpeed;
为了在按下 x 时提高速度,请执行
private void Update()
{
Vector2 mi = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
mv = mi.normalized * speed;
if(Input.GetKey(KeyCode.X) && energy > 0)
{
// Reduce energy by decreaseSpeed per second
energy -= decreaseSpeed * Time.deltaTime;
// if needed avoid negative value
energy = Mathf.Max(0, energy);
// double the move distance
mv *= 2;
}
}
顺便说一句,建议在FixedUpdate
中使用Time.deltaTime
而不是Time.fixedDeltaTime
(见Time.fixedDeltaTime
(
Update
检查冲刺轴(在项目输入设置中创建Sprint
轴(。另外,有一个变量来表示冲刺时能量棒消耗的速度:
public float energyBarDrainRate = 1f;
private bool isSprinting = false;
void Update() {
isSprinting = Input.GetAxis("Sprint") > 0f;
Vector2 mi = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
mv = mi.normalized * speed;
}
然后在 fixedupdate 中,检查您的能量条是否有足够的能量条来消耗该帧,如果确实如此,则耗尽它并提高该帧的有效移动速度:
private void FixedUpdate() {
float energyToDrain = energyBarDrainRate * Time.deltaTime
bool drainSprint = energyAmount > energyToDrain ;
float effectiveMv = mv;
if (drainSprint && isSprinting) {
effectiveMv = mv * 2f;
energyAmount -= energyToDrain;
}
rb.MovePosition(rb.position + effectiveMv * Time.deltaTime);
}