简体   繁体   中英

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:

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM