Version: 2022.2
public Vector3 velocity ;

描述

刚体的速度矢量。它表示刚体位置的变化率。

在大多数情况下,不应该直接修改速度,因为这可能导致行为失真 - 改用 AddForce 请勿在每个物理步骤中设置对象的速度,这将导致不真实的物理模拟。 需要更改速度的一个典型用法是第一人称射击游戏中的跳跃动作设计,因为此时需要立即更改速度。

**注意:**velocity 是世界空间属性。

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; } } } }

Note: A velocity in Unity is units per second. The units are often thought of as metres but could be millimetres or light years. Unity velocity also has the speed in X, Y, and Z defining the direction. Additionally, setting the linear velocity of a kinematic rigidbody is not allowed and will have no effect.