C# 当能量>;=10,然后每秒移除能量x?
我正在unity内进行一些FPS游戏开发,目前有一个角色能够运行,并使用以下变量进行冲刺:C# 当能量>;=10,然后每秒移除能量x?,c#,unity3d,C#,Unity3d,我正在unity内进行一些FPS游戏开发,目前有一个角色能够运行,并使用以下变量进行冲刺: public float regSpeed = 5; public float sprint = 7; public int energy = 100; 以及以下代码: var speed = regSpeed; //Left and Right MoveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vert
public float regSpeed = 5;
public float sprint = 7;
public int energy = 100;
以及以下代码:
var speed = regSpeed;
//Left and Right
MoveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
MoveDirection = transform.TransformDirection(MoveDirection);
MoveDirection *= speed;
//Sprint
if (energy >= 10 & Input.GetKey("left shift") || Input.GetKey("right shift")){
MoveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
MoveDirection = transform.TransformDirection(MoveDirection);
MoveDirection *= sprint;
我每秒钟都在努力消除能量。我猜我应该使用
Time.DeltaTime
或for/while循环中的某个东西每秒移除X个能量 您可以实现monobhavior.Update()方法。获取每个帧中Time.deltaTime的值,并累积该值。当累积值大于(1s*1000ms)时,减小能量。(当然,将累计值重置为cero)
更新每帧调用一次,可能需要多次。我建议使用FixedUpdate()以固定速率(不是每帧调用一次)来完成相同的任务
看到这里的区别了吗
存储
日期时间可能更可靠。现在,当sprint开始时,存储对象。然后,在之后的任何时刻,您都可以根据当前的DateTime.Now
计算剩余的能量。你可以连接到一个我相信的事件(我的Unity有点生疏),它是在运动过程中经常触发的,对吗?既然你唯一会消除能量的时间是在你短跑时,那么为什么不在你的短跑代码中减少能量呢,如果(能量>=10&Input.GetKey(“左移”)| | Input.GetKey(“右移”){energy-=5;}并相应地调整数量,直到你的能量在游戏执行时消耗殆尽。