0
\$\begingroup\$

I have this C# code for rotating the camera with the mouse:

public float mouseSensitivity = 100.0f;
public float clampAngle = 80.0f;

private float rotY = 0.0f; // rotation around the up/y axis
private float rotX = 0.0f; // rotation around the right/x axis

void Start()
{
    Screen.lockCursor = true;
    Vector3 rot = transform.localRotation.eulerAngles;
    rotY = rot.y;
    rotX = rot.x;
}

void Update()
{
    float mouseX = Input.GetAxis("Mouse X");
    float mouseY = -Input.GetAxis("Mouse Y");

    rotY += mouseX * mouseSensitivity * Time.deltaTime;
    rotX += mouseY * mouseSensitivity * Time.deltaTime;

    rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);

    Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
    transform.rotation = localRotation;
    transform.parent.transform.rotation = Quaternion.Euler(0.0f, rotY, 0.0f);
}

The script is on the camera, and camera object is a child to the player object. Now I want to move the player object in the direction the camera is facing, how do I do this?

\$\endgroup\$
1

1 Answer 1

2
\$\begingroup\$

Just add a CharacterController component to the player (the parent of the camera), and use this script:

public float mouseSensitivity = 100.0f;
public float clampAngle = 80.0f;

private float rotY = 0.0f; // rotation around the up/y axis
private float rotX = 0.0f; // rotation around the right/x axis

GameObject player;
public CharacterController controller;
public float speed = 6f;


void Start()
{
    Screen.lockCursor = true;
    Vector3 rot = transform.localRotation.eulerAngles;
    rotY = rot.y;
    rotX = rot.x;

    player = this.transform.parent.gameObject; // Getting the parent object.
    controller = player.GetComponent<CharacterController>(); // You can use the getcomponent in child instead
}

void Update()
{
    float mouseX = Input.GetAxis("Mouse X");
    float mouseY = -Input.GetAxis("Mouse Y");

    rotY += mouseX * mouseSensitivity * Time.deltaTime;
    rotX += mouseY * mouseSensitivity * Time.deltaTime;

    rotX = Mathf.Clamp(rotX, -clampAngle, clampAngle);

    Quaternion localRotation = Quaternion.Euler(rotX, rotY, 0.0f);
    transform.rotation = localRotation;
    transform.parent.transform.rotation = Quaternion.Euler(0.0f, rotY, 0.0f);

    float horizontal = Input.GetAxisRaw("Horizontal");
    float vertical = Input.GetAxisRaw("Vertical");
    Vector3 Direction = (player.transform.forward * vertical + player.transform.right * horizontal).normalized;

    controller.Move(Direction * speed * Time.deltaTime);

}

This will move the player with the ASDW or the arrows with the speed you want (using the speed variable).

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .