Version: 2021.3
public Vector2 velocity ;

描述

刚体的线性速度,采用单位/秒形式。

速度被指定为具有 X 和 Y 方向(在 2D 物理中,没有 Z 方向)分量的矢量。我们通常不直接设置该值,而是使用 forces。在 Inspector 中,禁用阻力可停止速度的逐渐衰减。

另请参阅:AddForcedragangularVelocityRigidbody.velocity

//Create a new 2D Sprite GameObject and attach this script to it.

//This script moves a GameObject up or down when you press the up or down arrow keys. //The velocity is set to the Vector2() value. Unchanging the Vector2() keeps the //GameObject moving at a constant rate.

using UnityEngine;

public class ExampleClass : MonoBehaviour { private Rigidbody2D rb;

private float t = 0.0f; private bool moving = false;

void Awake() { rb = gameObject.AddComponent<Rigidbody2D>() as Rigidbody2D; rb.bodyType = RigidbodyType2D.Kinematic; }

void Start() { gameObject.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("image128x128"); gameObject.transform.Translate(0.0f, 0.0f, 0.0f); }

void Update() { //Press the Up arrow key to move the RigidBody upwards if (Input.GetKey(KeyCode.UpArrow)) { rb.velocity = new Vector2(0.0f, 2.0f); moving = true; t = 0.0f; }

//Press the Down arrow key to move the RigidBody downwards if (Input.GetKey(KeyCode.DownArrow)) { rb.velocity = new Vector2(0.0f, -1.0f); moving = true; t = 0.0f; }

if (moving) { // Record the time spent moving up or down. // When this is 1sec then display info t = t + Time.deltaTime; if (t > 1.0f) { Debug.Log(gameObject.transform.position.y + " : " + t); t = 0.0f; } } } }