繁体   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