0
\$\begingroup\$

The camera script is a 3rd person orbit camera, when I look straight it does what it supposed to do which is walk in the direction the camera is pointing, but when the camera is looking down from above the player, the camera's forward is now up. This means when I press W to go forwards I go into the ground and when I press S it goes upwards.

Here is my movement script:

    private void FixedUpdate()
    {
    float x = Input.GetAxisRaw("Horizontal");
    float z = Input.GetAxisRaw("Vertical");

    Vector3 moveDirection = Vector3.zero;
    moveDirection += Camera.main.transform.right;
    moveDirection += Camera.main.transform.forward;
    moveDirection.y = 0;
    // Rotation
    if (x != 0 || z != 0)
    {
        anim.SetBool("Walking", true);
        if (x != 0)
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(moveDirection), 0.4f);
        }
        else
        {
            transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, Camera.main.transform.localEulerAngles.y, transform.localEulerAngles.z);
        }

    }
    else
    {
        anim.SetBool("Walking", false);
    }
    // Moving
    if (Input.GetKey(KeyCode.LeftShift) && !idle)
    {
        anim.SetBool("Running", true);
        rb.position += z * Camera.main.transform.forward * Time.deltaTime * runSpeed;
        rb.position += x * Camera.main.transform.right * Time.deltaTime * runSpeed;
    }
    else
    {
        anim.SetBool("Running", false);

        rb.position += z * Camera.main.transform.forward * Time.deltaTime * moveSpeed;
        rb.position += x * Camera.main.transform.right * Time.deltaTime * moveSpeed;
    }
}

while I'm asking, the movement script gets doubled when two keys are pressed, how do I fix it while keeping the same functionality of my current movement script?

\$\endgroup\$
1
\$\begingroup\$

This is normal behavior for the code you've written. You have to design your code around this issue.

You need a parent object for your camera which is always facing the horizon and can only turn left or right. So, while your camera is looking at the ground, your parent object will be looking towards the horizon. Then you just move your parent object instead of moving the camera itself.

I can't really write any code for this since this is not actually a coding problem but a system design problem. (i.e. your code is working the way it's supposed to but the system should be designed around how the code would work)

\$\endgroup\$
  • \$\begingroup\$ okay i will try this \$\endgroup\$ – Voon Van Eustace Jan 6 '18 at 6:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.