Skip to content

Instantly share code, notes, and snippets.

@AngryAnt
Created July 2, 2012 11:14
Show Gist options
  • Save AngryAnt/3032737 to your computer and use it in GitHub Desktop.
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.
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