簡體   English   中英

Unity3D 字符不朝其面對的方向移動

[英]Unity3D character not moving in the direction its facing

我有兩個腳本:一個用於我的玩家移動,另一個用於我的鼠標外觀。 問題是當我朝一個方向看時,我的玩家會朝另一個方向移動。

這是我的鼠標查看腳本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseLook : MonoBehaviour
{
// Mouse Direction
private Vector2 mD;

private Transform myBody;

// Start is called before the first frame update
void Start()
{
    myBody = this.transform.parent.transform;
}

// Update is called once per frame
void Update()
{
    // How much has the mouse moved?
    Vector2 mC = new Vector2 (Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));

    mD += mC;

    this.transform.localRotation = Quaternion.AngleAxis(-mD.y, Vector3.right);

    myBody.localRotation = Quaternion.AngleAxis(mD.x, Vector3.up);
     }
}

這是我的玩家移動腳本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
Vector3 moveVector = Vector3.zero;
CharacterController characterController;

public float MoveSpeed;
public float JumpSpeed;
public float Gravity;

// Start is called before the first frame update
void Start()
{
    characterController = GetComponent<CharacterController>();
}

// Update is called once per frame
void Update()
{
    moveVector.x = Input.GetAxis("Horizontal") * MoveSpeed;
    moveVector.z = Input.GetAxis("Vertical") * MoveSpeed;

    if (characterController.isGrounded && Input.GetButton("Jump"))
    {
        moveVector.y = JumpSpeed;
    }

    moveVector.y -= Gravity * Time.deltaTime;

    characterController.Move(moveVector * Time.deltaTime);
    }
}

我是統一的新手,所以如果您知道答案,如果您能解釋一下,我將不勝感激:)

一種快速解決問題的方法是將moveVector乘以玩家的旋轉:

characterController.Move(transform.rotation * moveVector * Time.deltatime);

這將通過玩家的旋轉來旋轉您的矢量,使其指向相同的方向。

另一種方法是使用transform.forwardtransform.right

float moveX = Input.GetAxis("Horizontal") * MoveSpeed;
float moveZ = Input.GetAxis("Vertical") * MoveSpeed;

movementVector = (transform.forward * moveZ) + (transform.right * moveX);

transform.forward獲取 object 的前向向量,因此您可以使用它來確保角色向前移動。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM