[英]Unity3D character facing in the direction it’s moving
我正在制作一個游戲,它包含行星重力,如何使玩家朝其移動方向看,如果可以將其插入運動代碼中,將對您有所幫助
using UnityEngine;
public class PlayerMovementScript : MonoBehaviour {
public float moveSpeed;
private Vector3 moveDirection;
void Update()
{
moveDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
}
void FixedUpdate()
{
GetComponent<Rigidbody>().MovePosition(GetComponent<Rigidbody>().position + transform.TransformDirection(moveDirection) * moveSpeed * Time.deltaTime);
}
}
您可以通過使用剛體的速度來觀察移動方向。
transform.rotation = Quaternion.LookRotation(rb.velocity);
如果要平滑過渡:
Quaternion desiredRotation = Quaternion.LookRotation(rb.velocity);
transform.rotation = Quaternion.Slerp(transform.rotation, desiredRotation, Time.deltaTime);
假定此腳本已附加到要指向其移動方向的對象上,請嘗試執行此操作。
void Update()
{
moveDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
Vector3 lookDirection = moveDirection + gameObject.Transform.Position;
gameObject.Transform.LookAt(lookDirection);
}
由於您的moveDirection已標准化,因此必須將其添加到當前位置才能在對象的本地空間中獲取moveDirection。 然后,您可以LookAt()
指向它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.