Skip to content

Instantly share code, notes, and snippets.

@JonahGrimm
Created January 28, 2023 04:15
Show Gist options
  • Save JonahGrimm/0a1744e0ec5dc2285f3a5a12699282a6 to your computer and use it in GitHub Desktop.
Save JonahGrimm/0a1744e0ec5dc2285f3a5a12699282a6 to your computer and use it in GitHub Desktop.
using Cinemachine;
using UnityEngine;
public static class MethodExtensions
{
public static Vector3 WorldToViewportPoint(this CinemachineVirtualCameraBase vcam, Vector3 position)
{
// CyRaid https://forum.unity.com/threads/reproducing-cameras-worldtocameramatrix.365645/
Matrix4x4 worldToCameraMatrix = Matrix4x4.Inverse(Matrix4x4.TRS(vcam.State.FinalPosition, vcam.State.FinalOrientation, new Vector3(1, 1, -1)));
Matrix4x4 projectionMatrix = Matrix4x4.Perspective(vcam.State.Lens.FieldOfView, vcam.State.Lens.Aspect, vcam.State.Lens.NearClipPlane, vcam.State.Lens.FarClipPlane);
// Thanks to bgolus for being the hero of the Unity community
// https://forum.unity.com/threads/camera-worldtoviewportpoint-math.644383/
Vector4 worldPos = new Vector4(position.x, position.y, position.z, 1.0f);
Vector4 viewPos = worldToCameraMatrix * worldPos;
Vector4 projPos = projectionMatrix * viewPos;
Vector3 ndcPos = new Vector3(projPos.x / projPos.w, projPos.y / projPos.w, projPos.z / projPos.w);
return new Vector3(ndcPos.x * 0.5f + 0.5f, ndcPos.y * 0.5f + 0.5f, -viewPos.z);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment