Skip to content

Instantly share code, notes, and snippets.

@CharlieHess
Created October 30, 2022 01:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CharlieHess/16bd49d120ad04eb857f8ead326cd33c to your computer and use it in GitHub Desktop.
Save CharlieHess/16bd49d120ad04eb857f8ead326cd33c to your computer and use it in GitHub Desktop.
Generates an isometric aligned polygon collider in a box shape
using System.Collections.Generic;
using Sirenix.OdinInspector;
using UnityEngine;
public enum IsoAlignmentOption {
NorthSouth,
EastWest,
NorthEastSouthWest,
NorthWestSouthEast
}
[RequireComponent(typeof(PolygonCollider2D))]
public class IsoAlignedBoxCollider2D : MonoBehaviour {
[OnValueChanged("UpdateCollider")]
public int width, height;
[OnValueChanged("UpdateCollider")]
public IsoAlignmentOption alignment;
protected PolygonCollider2D _collider;
protected Vector2[] _points = new Vector2[4];
/// <summary>
/// Set this to match your pixel grid size.
/// </summary>
static readonly float GridSize = 1 / 32f;
/// <summary>
/// Unlike the traditional isometric projection of 30°, or the 3D modeler's
/// isometric of 27.368°, in pixel art the ideal projection creates exactly
/// two pixels of width (run) for every pixel of height (rise).
///
/// To find an angle from the rise and the run, use atan(rise, run). That
/// gives us atan(1 / 2) = 26.565°. That is our *pixel-perfect* isometric
/// angle.
/// </summary>
static readonly float IsometricAngle = Mathf.Rad2Deg * Mathf.Atan(1f / 2f);
static readonly Dictionary<IsoAlignmentOption, Matrix4x4> RotationMatrices =
new Dictionary<IsoAlignmentOption, Matrix4x4> {
{ IsoAlignmentOption.NorthSouth, Matrix4x4.Rotate(Quaternion.Euler(0, 0, 0)) },
{ IsoAlignmentOption.EastWest, Matrix4x4.Rotate(Quaternion.Euler(0, 0, 90)) },
{ IsoAlignmentOption.NorthEastSouthWest, Matrix4x4.Rotate(Quaternion.Euler(0, 0, IsometricAngle)) },
{ IsoAlignmentOption.NorthWestSouthEast, Matrix4x4.Rotate(Quaternion.Euler(0, 0, -IsometricAngle)) }
};
[OnInspectorInit]
protected void SetColliderForEditor() {
_collider = GetComponent<PolygonCollider2D>();
}
protected void Start() {
_collider = GetComponent<PolygonCollider2D>();
UpdateCollider();
}
protected void UpdateCollider() {
var halfSize = new Vector2(width, height) * GridSize / 2f;
_points[0] = new Vector2(-halfSize.x, halfSize.y);
_points[1] = new Vector2(halfSize.x, halfSize.y);
_points[2] = new Vector2(halfSize.x, -halfSize.y);
_points[3] = new Vector2(-halfSize.x, -halfSize.y);
for (var i = 0; i < _points.Length; i++) {
_points[i] = RotationMatrices[alignment].MultiplyPoint(_points[i]);
}
_collider.points = _points;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment