My players 'light' rotation gets limited as i move away from 0,0,0, for unknown reasons

2024-10-19 17-03-17

it says im a new user so i cant upload the code so

using Cinemachine.Utility;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerLight : MonoBehaviour
{
    [SerializeField] private FieldOfView fieldOfView;
    private Camera mainCam;
    private Vector3 mousePos;
    public Transform playerTransform;

    // Start is called before the first frame update
    void Start()
    {
        mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
    }


    // Update is called once per frame
    void Update()
    {

        // likely the culprit to the buggy fov effect
        mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
        // end culprit

        Vector3 rotation = mousePos;

        var rotZ = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;

        transform.rotation = Quaternion.Euler(0, 0, rotZ);

        fieldOfView.SetAimDirection(mousePos);
        fieldOfView.SetOrigin(playerTransform.position);
    }
}

Gonna be honest im really at a loss for how to fix this so any help would be monumental

Try changing line 30 to:

Vector3 rotation = mousePos - transform.position;

NOTE: if you execute this code

as rotation’s magnitude becomes zero, the rotation of such a vector is undefined and will also become unstable due to floating point imprecision.

You may be able to simply drive transform.forward (or transform.up when in 2D) equal to your movement vector, never when it falls below a certain magnitude threshold.

Otherwise, use Mathf.Atan2() to derive heading from cartesian coordinates:

Sine/Cosine/Atan2 (sin/cos/atan2) and rotational familiarity and conventions

1 Like