Guest User

Magnet.cs

a guest
Jan 16th, 2015
344
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.    ///////////////////////////////////////////
  2.   // "Magnet.cs" - Runtime object snapping //
  3.  // Written by Michael Wion on 01/15/2015 //
  4. ///////////////////////////////////////////
  5.  
  6. using UnityEngine;
  7. using System.Collections;
  8. using System.Collections.Generic;
  9.  
  10. [System.Serializable]
  11. public struct MagnetizedItem
  12. {
  13.     public Vector3 polarity;
  14.     public Vector3 offset;
  15.     public GameObject[] allowed;
  16.  
  17.     public void Attach (GameObject obj) {
  18.         Magnet m = Magnet.GetInstance ();
  19.         Transform mTransform = m.transform;
  20.         GameObject mObject = mTransform.gameObject;
  21.         Bounds mBounds = mObject.renderer.bounds;
  22.         Bounds oBounds = obj.renderer.bounds;
  23.         polarity.Normalize();
  24.         Vector3 direction = new Vector3(
  25.             ((mBounds.size.x / 2) + (oBounds.size.x / 2)) * polarity.x,
  26.             ((mBounds.size.y / 2) + (oBounds.size.y / 2)) * polarity.y,
  27.             ((mBounds.size.z / 2) + (oBounds.size.z / 2)) * polarity.z
  28.         );
  29.         obj.transform.position = (mTransform.position + direction) + offset;
  30.     }
  31. }
  32.  
  33. public class Magnet : MonoBehaviour
  34. {
  35.     private static Magnet _instance;
  36.     public List<MagnetizedItem> items;
  37.  
  38.     public static Magnet GetInstance() {
  39.         return _instance;
  40.     }
  41.  
  42.     public void Awake() {
  43.         _instance = this;
  44.         if(items == null) items = new List<MagnetizedItem>();
  45.     }
  46.  
  47.     void Start() {
  48.         foreach(MagnetizedItem item in items) {
  49.             foreach(GameObject obj in item.allowed) {
  50.                 item.Attach(obj);
  51.             }
  52.         }
  53.     }
  54. }
RAW Paste Data