This file contains 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; | |
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