[英]Unity3D character not moving in the direction its facing
I have two scripts: one for my player movement and another for my mouse-look.我有两个脚本:一个用于我的玩家移动,另一个用于我的鼠标外观。 The problem is that when I look in a direction my player moves in another.
问题是当我朝一个方向看时,我的玩家会朝另一个方向移动。
Here is my Mouse Look Script:这是我的鼠标查看脚本:
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);
}
}
Here is my player movement script:这是我的玩家移动脚本:
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);
}
}
I am new to unity, so if you do know the answer I would appreciate it if you would explain it:)我是统一的新手,所以如果您知道答案,如果您能解释一下,我将不胜感激:)
One way to quickly fix what you have is to multiply your moveVector
by the rotation of the player:一种快速解决问题的方法是将
moveVector
乘以玩家的旋转:
characterController.Move(transform.rotation * moveVector * Time.deltatime);
This will rotate your vector by the rotation of the player making it point in the same direction.这将通过玩家的旋转来旋转您的矢量,使其指向相同的方向。
Another way to do this would be to use transform.forward
and transform.right
:另一种方法是使用
transform.forward
和transform.right
:
float moveX = Input.GetAxis("Horizontal") * MoveSpeed;
float moveZ = Input.GetAxis("Vertical") * MoveSpeed;
movementVector = (transform.forward * moveZ) + (transform.right * moveX);
transform.forward
gets the forward vector of your object so you can use it to make sure the character moves forward on its forward. transform.forward
获取 object 的前向向量,因此您可以使用它来确保角色向前移动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.