[英]Unity c# - move player in direction he's facing (instead global space)
所以我有這個用於玩家移動+旋轉的腳本。 問題是當我用我的角色轉身然后按鍵前進時,由於全局空間,它會變得很糟糕......例如,當我向左轉然后按前進鍵時,它會返回並前進而不是進去我的角色所面對的方向。 我是 c# 和團結的新手。 所以我很樂意提供任何幫助。 謝謝!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SharkMovement : MonoBehaviour
{
private Rigidbody rb;
float xInput;
float zInput;
public float moveSpeed;
public float rotateSpeed;
private Vector3 direction;
private Vector3 fwd;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
// Pohyb ryby
xInput = Input.GetAxisRaw("Horizontal2");
zInput = Input.GetAxisRaw("Vertical2");
direction = new Vector3(xInput, 0.0f, zInput);
if (direction != Vector3.zero)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), rotateSpeed * Time.deltaTime);
}
rb.MovePosition(transform.position + moveSpeed * Time.deltaTime * direction);
}
}
您可以使用Transform.forward來獲取 object 的前向向量。 假設 zInput 是您的 Forward/Backward 輸入,這樣的事情會起作用。
xInput = Input.GetAxisRaw("Horizontal2");
zInput = Input.GetAxisRaw("Vertical2");
direction = new Vector3(xInput, 0.0f, 0.0f) + (zInput * transform.forward);
將xInput
與transform.right
相乘,將zInput
與transform.forward
相乘,然后將它們相加:
xInput = Input.GetAxisRaw("Horizontal2");
zInput = Input.GetAxisRaw("Vertical2");
direction = xInput * transform.right + zInput * transform.forward;
您可能還應該將幅度限制為 1,因此對角線移動不會比正交移動快:
xInput = Input.GetAxisRaw("Horizontal2");
zInput = Input.GetAxisRaw("Vertical2");
direction = xInput * transform.right + zInput * transform.forward;
direction = direction.normalized * Mathf.Min(1f, direction.magnitude);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.