Search code examples
c#unity-game-engineangle

How to properly get angle of another GameObject's position relative to player's position with the player's camera in account


I am currently trying to make a grenade indicator that activates if the player is too close to the current grenade.

I want the indicator to always point correctly at where the grenade is, in accordance with where the player is and where the camera is pointing at.

However, I am currently getting... well whatever this is: https://streamable.com/hfrgko

Here is the function for the grenade indicator:

private void RotateIndicator()
    {
        if(grenadeCollider != null)
        {
            Vector3 camForward = FPSCamera.transform.forward;
            Vector3 targetDirToCam = grenadeCollider.transform.position - FPSCamera.transform.position;

            float rotation = Vector3.Cross(camForward, targetDirToCam).z * -180;

            GrenadeIndicatorUI.transform.rotation = Quaternion.Euler(new Vector3(0, 0, rotation));
        }
    }

I'm not really good at rotations and vectors. If anyone has a solution to this, I would very much appreciate it if you can explain what I've done wrong and provide an explanation of the solution so that I am able to understand.

Much thanks


Solution

  • Hi you can refer to this video: https://www.youtube.com/watch?v=BC3AKOQUx04

    seems like it is what you need: enter image description here