【问题标题】:Unity3D character not moving in the direction its facingUnity3D角色没有朝其面对的方向移动
【发布时间】:2021-03-30 15:44:41
【问题描述】:

我有两个脚本:一个用于我的玩家移动,另一个用于我的鼠标外观。 问题是当我朝一个方向看时,我的玩家会朝另一个方向移动。

这是我的鼠标查看脚本:

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);
    }
}

我是统一的新手,所以如果你知道答案,如果你能解释一下,我将不胜感激:)

【问题讨论】:

  • 欢迎来到 SO。请查看How to Ask。尽可能具体地说明当前正在发生的事情和负责的代码(例如,“玩家移动另一个”是什么意思?)。

标签: c# unity3d


【解决方案1】:

一种快速解决问题的方法是将您的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 获取对象的前向向量,因此您可以使用它来确保角色向前移动。

【讨论】:

  • 感谢您的回答,但它似乎不起作用?
  • 你在做什么解决方案?
  • 我在做第一个
  • 有什么问题?方向是随机的吗?
  • 当我向右看时,玩家会向前移动,因为它不知道它有一个鼠标看脚本。例如我看 x 方向,玩家认为我仍然看 z 方向,所以当我向前按下时,即使我看 x 方向,它仍然是 z
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多