Skip to content

Instantly share code, notes, and snippets.

@goshdarngames
Created September 13, 2015 17:44
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save goshdarngames/7177ac4fc14209462438 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System;
using System.Collections;
public class ConfineToCircle : MonoBehaviour
{
/***************************************************************************
* INSPECTOR DATA
**************************************************************************/
public float objectRadius;
public float circleRadiusSquared;
/***************************************************************************
* FIXED DATA
**************************************************************************/
void FixedUpdate ()
{
Rigidbody2D rb2D = GetComponent<Rigidbody2D> ();
//calculate the sqrd distance of this object from the center + radius
//i.e. how far the outer edge of this object is from center
//We use the Squared distances because we are using Pythagoras'
//theorem (a squared + b squared) to calculate the distance from
//centre and it is unecessary (and computationally faster) to
//square root the result since we are just comparing the magnitude.
//Note: We don't use position.sqrMagnitude because we have to account
// for the object's radius as well and can't just add that to
// the result of square magnitude.
float distanceSquared
= (float)
(Math.Pow(Math.Abs(transform.position.x) + objectRadius, 2)
+
Math.Pow(Math.Abs(transform.position.y) + objectRadius , 2));
//compare distance from centre to circle radius
if( distanceSquared >= circleRadiusSquared)
{
//use position + velocity to ensure object is moving away from the
//centre
Vector2 posV2 = new Vector2(transform.position.x,
transform.position.y);
Vector2 nextPos = posV2+rb2D.velocity;
//if we are moving away from center
if(posV2.SqrMagnitude() < nextPos.SqrMagnitude() )
{
//apply negative force to stop object
rb2D.AddForce (rb2D.velocity * -1f, ForceMode2D.Impulse);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment