Let an object rotate and move in the direction of the camera

I am creating this 3D game third person game. I have the main camera as the child of player. So far I am able to move the player, and look around using the mouse. However, my character doesn’t rotate with camera and move in that direction. I suppose I want him to only rotate on the y axis. So left and right . Any help would be great my code is below:

Code attached to the camera:
csharp** ** //Horizental speed private float speedH; //Vertical Speed private float speedV; private float yaw; private float pitch; private float distance = 0.5f; // Use this for initialization void Start () { speedH= 2.0f; speedV = 2.0f; yaw = 0.0f; pitch = 0.0f; } // Update is called once per frame void Update () { yaw += speedH * Input.GetAxis("Mouse X"); pitch -= speedV * Input.GetAxis("Mouse Y"); transform.eulerAngles = new Vector3(pitch, yaw, 0.0f); }** **

Code attached to the player:

  private float velocity;
    // Use this for initialization
    void Start () {
        velocity = 0.9f * Time.deltaTime;
    }
// Update is called once per frame
void Update () {
        setPlayerCorrdinates(velocity);
    }
    //Location of the player
    private void setPlayerCorrdinates(float coordintate)
    {
        //Move the player on the x,y,z
        //player.transform.position = new Vector3(coordintate, transform.position.y, transform.position.z);
        if (Input.GetKey(KeyCode.W))
            transform.Translate(velocity, 0, 0);
        else if (Input.GetKey(KeyCode.A))
            transform.Translate(0, 0, velocity);
        else if (Input.GetKey(KeyCode.D))
            transform.Translate(0, 0, -velocity);
        else if (Input.GetKey(KeyCode.S))
            transform.Translate(-velocity, 0, 0);
    }

When the camera is a child, you needn’t move the camera (rotate it), unless you want some rotation that is more or different from the character.

If you wanted ‘W’ = forward, and ‘S’ = backward, then ‘a’ and ‘d’ could rotate… just as an example.

float mouseRot = Input.GetAxis("Mouse X");
mouseRot *= mouseRotationSpeed; // say this is 1 or 2 to try.
transform.rotation *= Quaternion.Euler(0, mouseRot, 0);

You could try that, while commenting out the left/right movement for now.

That’s just one idea. :slight_smile:

1 Like