Created
July 2, 2012 11:14
-
-
Save AngryAnt/3032737 to your computer and use it in GitHub Desktop.
Example of simple component for keeping objects inside defined bounds by physically repelling them back when they exit.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
[RequireComponent (typeof (BoxCollider))] | |
public class ContainerGravity : MonoBehaviour | |
{ | |
public float strength = 10.0f; | |
void Start () | |
{ | |
if (!collider.isTrigger) | |
{ | |
Debug.LogError ("ContainerGravity collider must be a trigger", this); | |
enabled = false; | |
return; | |
} | |
} | |
void OnTriggerExit (Collider other) | |
{ | |
StartCoroutine (BringBack (other)); | |
} | |
IEnumerator BringBack (Collider other) | |
{ | |
Bounds bounds; | |
Rigidbody otherRigidbody = other.transform.root.GetComponentInChildren<Rigidbody> (); | |
while (enabled) | |
{ | |
bounds = collider.bounds; | |
bounds.Encapsulate (other.bounds); | |
if (bounds == collider.bounds) | |
{ | |
yield break; | |
} | |
else | |
{ | |
otherRigidbody.AddForce ( | |
(transform.position - other.transform.position).normalized * strength - | |
otherRigidbody.velocity, | |
ForceMode.VelocityChange | |
); | |
yield return null; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment