3
votes

I'm trying to make an first person camera and the camera and player movement work exactly how I need them to however my issue now is that if I look to the right with the camera and press W to move forward it moves forward an accordance to the game world rather than the direction the camera is looking.

I've tried changing the parenting, or using a transform to link the player and camera together.

// Simple Player movement
Rigidbody rb;
public float speed;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    float mH = Input.GetAxis("Horizontal");
    float mV = Input.GetAxis("Vertical");
    rb.velocity = new Vector3(mH * speed, rb.velocity.y, mV * speed);
}
// Camera controls (separate script)
private Transform playerBody;

void update()
{
    CameraRotation();
}

private void CameraRotation()
{
    float mouseX = Input.GetAxis(mouseXInputName) * mouseSensitivity * Time.deltaTime;
    float mouseY = Input.GetAxis(mouseYInputName) * mouseSensitivity * Time.deltaTime;
    xAxisClamp += mouseY;

    if (xAxisClamp > 90.0f)
    {
        xAxisClamp = 90.0f;
        mouseY = 0.0f;
        ClampAxisRotationToValue(270.0f);
    }
    else if (xAxisClamp < -90.0f)
    {
        xAxisClamp = -90.0f;
        mouseY = 0.0f;
        ClampAxisRotationToValue(90.0f);
    }
    transform.Rotate(Vector3.left * mouseY);
    playerBody.Rotate(Vector3.up * mouseX);
}

With the last line playerBody.rotate I was expecting it to rotate the Object the camera is attached to so when i press forward it would move forward in the direction the camera is looking but it still moves in its static X and Z while ignoring the cameras direction.

1

1 Answers

1
votes

When you're moving your character, you're setting its velocity relative to the world's axises and does not take object rotation into consideration.

To add object rotation into the input, simply base the input on the rotation like this:

void FixedUpdate()
{
    Vector3 mH = transform.right * Input.GetAxis("Horizontal");
    Vector3 mV = transform.forward * Input.GetAxis("Vertical");
    rb.velocity = (mH + mV) * speed;
}

The mH & mV should now be relative to where your object is facing because transform.forward (and .right) will be a representation of what "forward" is for your object.

And since GetAxis() will represent a number between -1 & 1 we're basically saying that the Input.GetAxis determines HOW MUCH forward we want to go. 1 or -1? Forward or backwards? forward * 1 or forward * -1. Same with strafing; right * 1 or right * -1.