刚体的速度矢量。它表示Rigidbody位置的变化率。
在大多数情况下,你不应该直接修改速度,因为这可能导致不真实的行为 - 使用AddForce而不是设置速度。不要在每次物理步骤中设置一个对象的速度,这会导致不真实的物理模拟。一个典型的用法是在第一人称射击游戏中跳跃时更改速度,因为你想要立即改变速度。
注意: 速度 是世界空间属性。
using UnityEngine; using System.Collections;
// The velocity along the y axis is 10 units per second. If the GameObject starts at (0,0,0) then // it will reach (0,100,0) units after 10 seconds.
public class ExampleClass : MonoBehaviour { public Rigidbody rb;
private float time = 0.0f; private bool isMoving = false; private bool isJumpPressed = false;
void Start() { rb = GetComponent<Rigidbody>(); }
void Update() { isJumpPressed = Input.GetButtonDown("Jump"); }
void FixedUpdate() { if (isJumpPressed) { // the cube is going to move upwards in 10 units per second rb.velocity = new Vector3(0, 10, 0); isMoving = true; Debug.Log("jump"); }
if (isMoving) { // when the cube has moved for 10 seconds, report its position time = time + Time.fixedDeltaTime; if (time > 10.0f) { Debug.Log(gameObject.transform.position.y + " : " + time); time = 0.0f; } } } }
注意: 在Unity中,速度的单位是每秒。单位通常是米,但也可能是毫米或光年。Unity的速度还有X、Y和Z方向的速度,以定义方向。另外,设置动力刚体的线性速度是不允许的,也不会产生任何效果。