0
\$\begingroup\$

I was following a unity tutorial to make my character face in the position the camera is facing. After I finished the editing the script, I got an error at runtime saying, "Look rotation viewing vector is zero." On the line :

  Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);
    orientation.forward = viewDir.normalized;

here is the rest of the code I wrote:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ThirdPersonCam : MonoBehaviour
{
     [Header("References")]
     public Transform orientation;
     public Transform player;
     public Transform playerObj;
     public Rigidbody rb;

     public float rotationSpeed;

    private void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

     void FixedUpdate()
     {
        Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);
        orientation.forward = viewDir.normalized;

        // rotate the playerObj
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");
        Vector3 inputDir = orientation.forward * verticalInput - orientation.right * horizontalInput;

        if(inputDir != Vector3.zero)
            playerObj.forward = Vector3.Slerp(playerObj.forward, inputDir.normalized, Time.deltaTime * rotationSpeed);
     }
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Lower down, you check whether a vector is zero before using it to assign a forward direction. Did you perhaps consider doing a similar check before the line that's throwing the error? \$\endgroup\$
    – DMGregory
    Jul 12 at 21:18

2 Answers 2

1
\$\begingroup\$

I added a if statement to check if the vector is zero:

if(viewDir != Vector3.zero){}

To:

Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);
orientation.forward = viewDir.normalized;

And it fixed the error.

\$\endgroup\$
0
\$\begingroup\$

The problem is that the camera's position is ending up at the same position as the player's position. So, when you do this:

Vector3 viewDir = player.position - new Vector3(transform.position.x, player.position.y, transform.position.z);

viewDir ends up as a (0, 0, 0), and that cannot be normalized.

If you want the camera to face the same direction as the player, you could do something like this

var playerDir = player.transform.forward;
var viewDir = new Vector3(playerDir.x, camera.transform.forward.y, playerDir.z);
orientation.forward = viewDir.normalized;
\$\endgroup\$
0

You must log in to answer this question.

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