Created
May 7, 2020 16:31
-
-
Save TelpeNight/7cedddf764f3d7f71400a7ff351e1f39 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
namespace Renovation.Perspective | |
{ | |
public class PerspectiveCollider : MonoBehaviour | |
{ | |
public PerspectiveLock Lock; | |
private BoxCollider2D _collider; | |
private Bounds bounds; | |
private void Start() | |
{ | |
var collider = GetComponent<BoxCollider2D>(); | |
bounds = collider.bounds; | |
Destroy(collider); | |
CreatePerspectiveCollider(); | |
} | |
private void CreatePerspectiveCollider() | |
{ | |
GameObject go = new GameObject(); | |
go.transform.parent = transform; | |
go.name = "ProjectionCollider2D"; | |
go.layer = gameObject.layer; | |
go.tag = gameObject.tag; | |
_collider = go.AddComponent<BoxCollider2D>(); | |
UpdatePerspectiveCollider(); | |
} | |
private void Update() | |
{ | |
UpdatePerspectiveCollider(); | |
} | |
private void UpdatePerspectiveCollider() | |
{ | |
Vector2 projectedMin = Projection(bounds.min); | |
Vector2 projectedMax = Projection(bounds.max); | |
Vector2 center = (projectedMin + projectedMax) / 2; | |
Vector2 size = (projectedMax - projectedMin); | |
_collider.transform.position = center; | |
_collider.size = size; | |
} | |
private Vector2 Projection(Vector3 point) | |
{ | |
Vector3 delta = (point - Lock._otherCam.transform.position).normalized; | |
float t = -Lock._otherCam.transform.position.z / delta.z; | |
return Lock._otherCam.transform.position + delta * t; | |
} | |
private void OnDestroy() | |
{ | |
Destroy(_collider.gameObject); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment