Version: 2021.3
public Vector3 up ;

描述

世界空间中变换的绿轴。

操作游戏对象在世界空间中变换的 Y 轴(绿轴)上的位置。与 Vector3.up 不同,Transform.up 在移动游戏对象的同时,还考虑其旋转。

旋转游戏对象时,表示游戏对象的 Y 轴的绿色箭头也会改变方向。Transform.up 沿绿色箭头所在的轴 (Y) 移动游戏对象。

要在沿 Y 轴移动 GameObject 时忽略旋转,请参阅 Vector3.up

using UnityEngine;

public class Example : MonoBehaviour { Rigidbody2D m_Rigidbody; float m_Speed;

void Start() { //Fetch the Rigidbody component you attach from your GameObject m_Rigidbody = GetComponent<Rigidbody2D>(); //Set the speed of the GameObject m_Speed = 10.0f; }

void Update() { if (Input.GetKey(KeyCode.UpArrow)) { //Move the Rigidbody upwards constantly at speed you define (the green arrow axis in Scene view) m_Rigidbody.velocity = transform.up * m_Speed; }

if (Input.GetKey(KeyCode.DownArrow)) { //Move the Rigidbody downwards constantly at the speed you define (the green arrow axis in Scene view) m_Rigidbody.velocity = -transform.up * m_Speed; }

if (Input.GetKey(KeyCode.LeftArrow)) { //rotate the sprite about the Z axis in the positive direction transform.Rotate(new Vector3(0, 0, 1) * Time.deltaTime * m_Speed, Space.World); }

if (Input.GetKey(KeyCode.RightArrow)) { //rotate the sprite about the Z axis in the negative direction transform.Rotate(new Vector3(0, 0, -1) * Time.deltaTime * m_Speed, Space.World); } } }