Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class Slicer2DAnchor : MonoBehaviour {
- public enum AnchorType {AttachRigidbody, CancelSlice};
- public Collider2D[] anchorColliders = new Collider2D[1];
- public AnchorType anchorType = AnchorType.AttachRigidbody;
- private List<Polygon> polygons = new List<Polygon>();
- private List<Collider2D> colliders = new List<Collider2D>();
- void Start () {
- bool addEvents = false;
- foreach(Collider2D collider in anchorColliders) {
- addEvents = true;
- }
- if (addEvents == false) {
- return;
- }
- Slicer2D slicer = GetComponent<Slicer2D> ();
- if (slicer != null) {
- slicer.AddResultEvent (OnSliceResult);
- slicer.AddEvent (OnSlice);
- }
- foreach(Collider2D collider in anchorColliders) {
- polygons.Add(Polygon.CreateFromCollider (collider.gameObject));
- colliders.Add(collider);
- }
- }
- Polygon GetPolygonInWorldSpace(Polygon poly) {
- return(poly.ToWorldSpace(colliders[polygons.IndexOf(poly)].transform));
- }
- bool OnSlice(Slice2D sliceResult)
- {
- switch (anchorType) {
- case AnchorType.CancelSlice:
- foreach (Polygon polyA in new List<Polygon>(sliceResult.polygons)) {
- bool perform = true;
- foreach(Polygon polyB in polygons) {
- if (MathHelper.PolyCollidePoly (polyA.pointsList, GetPolygonInWorldSpace(polyB).pointsList) ) {
- perform = false;
- }
- }
- if (perform) {
- return(false);
- }
- }
- break;
- default:
- break;
- }
- return(true);
- }
- void OnSliceResult(List<GameObject> sliceResult)
- {
- if (polygons.Count < 1)
- return;
- foreach (GameObject p in sliceResult) {
- Polygon polyA = Polygon.CreateFromCollider (p).ToWorldSpace (p.transform);
- bool perform = true;
- foreach(Polygon polyB in polygons) {
- if (MathHelper.PolyCollidePoly (polyA.pointsList, GetPolygonInWorldSpace(polyB).pointsList)) {
- perform = false;
- }
- }
- if (perform) {
- switch (anchorType) {
- case AnchorType.AttachRigidbody:
- if (p.GetComponent<Rigidbody2D> () == null) {
- p.AddComponent<Rigidbody2D> ();
- }
- p.GetComponent<Rigidbody2D> ().isKinematic = false;
- break;
- default:
- break;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement