-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathBoxColliderCasts.cs
89 lines (68 loc) · 2.5 KB
/
BoxColliderCasts.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
* Class to setup needed raycasts around a BoxCollider2D player for proper collision detection
*/
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
public class BoxColliderCasts : MonoBehaviour
{
public LayerMask collisionMask;
public float skinWidth = .015f;
public float distanceBetweenRays = .25f;
[HideInInspector] public BoxCollider2D boxCollider;
[HideInInspector] public int horizontalRayCount;
[HideInInspector] public int verticalRayCount;
[HideInInspector] public float horizontalRaySpacing;
[HideInInspector] public float verticalRaySpacing;
public RaycastOrigins raycastOrigins;
public BoxCastOrigins boxCastOrigins;
[HideInInspector] public float boundsWidth;
[HideInInspector] public float boundsHeight;
public virtual void Awake()
{
boxCollider = GetComponent<BoxCollider2D>();
}
public virtual void Start()
{
CalculateRaySpacing();
}
public void CalculateRaySpacing()
{
Bounds bounds = boxCollider.bounds;
// Skin width for ray detection even when boxCollider is flush against surfaces
bounds.Expand(skinWidth * -2);
boundsWidth = bounds.size.x;
boundsHeight = bounds.size.y;
horizontalRayCount = Mathf.RoundToInt(boundsHeight / distanceBetweenRays);
verticalRayCount = Mathf.RoundToInt(boundsWidth / distanceBetweenRays);
horizontalRaySpacing = bounds.size.y / (horizontalRayCount - 1);
verticalRaySpacing = bounds.size.x / (verticalRayCount - 1);
}
public void UpdateRaycastOrigins()
{
Bounds bounds = boxCollider.bounds;
// Skin width for ray detection even when boxCollider is flush against surfaces
bounds.Expand(skinWidth * -2);
// Match corners of box boxCollider
raycastOrigins.bottomLeft = new Vector2(bounds.min.x, bounds.min.y);
raycastOrigins.bottomRight = new Vector2(bounds.max.x, bounds.min.y);
raycastOrigins.topLeft = new Vector2(bounds.min.x, bounds.max.y);
raycastOrigins.topRight = new Vector2(bounds.max.x, bounds.max.y);
}
public void UpdateBoxCastOrigins()
{
Bounds bounds = boxCollider.bounds;
boxCastOrigins.bottomCenter = new Vector2(bounds.center.x, bounds.min.y);
boxCastOrigins.topCenter = new Vector2(bounds.center.x, bounds.max.y);
boxCastOrigins.leftCenter = new Vector2(bounds.min.x, bounds.center.y);
boxCastOrigins.rightCenter = new Vector2(bounds.max.x, bounds.center.y);
}
public struct RaycastOrigins
{
public Vector2 bottomLeft, bottomRight;
public Vector2 topLeft, topRight;
}
public struct BoxCastOrigins
{
public Vector2 bottomCenter, topCenter, leftCenter, rightCenter;
}
}