Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///////////////////////////////////////////
- // "Magnet.cs" - Runtime object snapping //
- // Written by Michael Wion on 01/15/2015 //
- ///////////////////////////////////////////
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- [System.Serializable]
- public struct MagnetizedItem
- {
- public Vector3 polarity;
- public Vector3 offset;
- public GameObject[] allowed;
- public void Attach (GameObject obj) {
- Magnet m = Magnet.GetInstance ();
- Transform mTransform = m.transform;
- GameObject mObject = mTransform.gameObject;
- Bounds mBounds = mObject.renderer.bounds;
- Bounds oBounds = obj.renderer.bounds;
- polarity.Normalize();
- Vector3 direction = new Vector3(
- ((mBounds.size.x / 2) + (oBounds.size.x / 2)) * polarity.x,
- ((mBounds.size.y / 2) + (oBounds.size.y / 2)) * polarity.y,
- ((mBounds.size.z / 2) + (oBounds.size.z / 2)) * polarity.z
- );
- obj.transform.position = (mTransform.position + direction) + offset;
- }
- }
- public class Magnet : MonoBehaviour
- {
- private static Magnet _instance;
- public List<MagnetizedItem> items;
- public static Magnet GetInstance() {
- return _instance;
- }
- public void Awake() {
- _instance = this;
- if(items == null) items = new List<MagnetizedItem>();
- }
- void Start() {
- foreach(MagnetizedItem item in items) {
- foreach(GameObject obj in item.allowed) {
- item.Attach(obj);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement