Created
March 29, 2021 14:49
-
-
Save paulmasri/f1b7d64a4b2281b597c47712d994c5c7 to your computer and use it in GitHub Desktop.
Unity Utility2D.cs
This file contains hidden or 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; | |
using System.Collections.Generic; | |
namespace PaulMasriStone.Utility2D | |
{ | |
public static class Utility2D | |
{ | |
public static bool IsPointWithinCollider2D(Vector2 targetPoint, Vector2 externalPoint, int layerMask = Physics2D.DefaultRaycastLayers) | |
{ | |
var direction = (targetPoint - externalPoint).normalized; | |
var tinyNudge = direction * 0.001f; // avoids Linecast hitting the same point over and over | |
RaycastHit2D hit; | |
int hitCount = 0; | |
var rayStart = externalPoint; | |
while (rayStart != targetPoint) { | |
hit = Physics2D.Linecast(rayStart, targetPoint, layerMask); | |
if (hit) | |
{ | |
hitCount++; | |
rayStart = hit.point + tinyNudge; | |
} | |
else | |
break; | |
} | |
return hitCount % 2 != 0; | |
} | |
public static bool IsPointWithinBounds(Vector2 targetPoint, Bounds bounds) | |
{ | |
var boundRect = new Rect((Vector2)bounds.min, (Vector2)bounds.size); | |
return boundRect.Contains(targetPoint); | |
} | |
public static Rect OrthographicRect(this Camera camera) | |
{ | |
var center = (Vector2)camera.transform.position; | |
var vExtent = camera.orthographicSize; | |
var hExtent = vExtent * camera.aspect; | |
var rect = new Rect(center.x - hExtent, center.y - vExtent, hExtent * 2f, vExtent * 2f); | |
return rect; | |
} | |
public static void SetPolygonColliderPath(ref PolygonCollider2D collider, Sprite sprite) | |
{ | |
// Remove existing path | |
collider.pathCount = 0; | |
// Set new path to match Custom Physics Shape of sprite (which must be set in Sprite Editor) | |
collider.pathCount = sprite.GetPhysicsShapeCount(); | |
var path = new List<Vector2>(); | |
for (int i = 0; i < collider.pathCount; i++) | |
{ | |
sprite.GetPhysicsShape(i, path); | |
collider.SetPath(i, path.ToArray()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment