描述

这是 MoveDirection 的 Right 状态。分配向右移动的功能。

使用 Right 状态,以可轻松识别的方式向右移动游戏对象 (1 , 0 , 0)。这种状态无需任何预定义功能。使用此状态之前,您应该先在代码中定义游戏对象要执行的操作。

//Attach this script to a GameObject with a Rigidbody component. Press the "Move Right" button in Game view to see it in action.

using UnityEngine; using UnityEngine.EventSystems;

public class MoveDirectionExample : MonoBehaviour { Vector3 m_StartPosition, m_StartForce; Rigidbody m_Rigidbody; //Use Enum for easy switching between direction states MoveDirection m_MoveDirection;

//Use these Vectors for moving Rigidbody components Vector3 m_ResetVector; Vector3 m_RightVector; const float speed = 5.0f;

void Start() { //You get the Rigidbody component attached to the GameObject m_Rigidbody = GetComponent<Rigidbody>(); //This starts with the Rigidbody not moving in any direction at all m_MoveDirection = MoveDirection.None;

//These are the GameObject’s starting position and Rigidbody position m_StartPosition = transform.position; m_StartForce = m_Rigidbody.transform.position;

//This Vector is set to 1 in the x axis (for moving in the right direction) m_RightVector = Vector3.right; //This Vector is zeroed out for when the Rigidbody should not move m_ResetVector = Vector3.zero; }

void Update() { //This switches the direction depending on button presses switch (m_MoveDirection) { //The starting state which resets the object case MoveDirection.None: //Reset to the starting position of the GameObject and Rigidbody transform.position = m_StartPosition; m_Rigidbody.transform.position = m_StartForce; //This resets the velocity of the Rigidbody m_Rigidbody.velocity = m_ResetVector; break;

//This is for moving right case MoveDirection.Right: //This moves the Rigidbody to the right m_Rigidbody.velocity = m_RightVector * speed; break; } }

void OnGUI() { //Press the reset Button to switch to no mode if (GUI.Button(new Rect(100, 0, 150, 30), "Reset")) { //Switch to start/reset case m_MoveDirection = MoveDirection.None; }

//Press the Left button to switch the Rigidbody direction to the right if (GUI.Button(new Rect(100, 30, 150, 30), "Move Right")) { //Switch to the left direction m_MoveDirection = MoveDirection.Right; } } }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961