- Home /
Trying to reverse planetary gravity
So this is what I'm trying to do. I have a 2D game, the player is a planet and can move around. The player has a gravity, so objects in the level will gravitate towards the player. I've also set it up so when the player hits the space bar their mass increases so objects gravitate towards them quicker. I have a video of this up here if it helps make it clearer: http://www.youtube.com/watch?v=eCE_kCcg2qA
To do this I'm using this script on the player's avatar object:
var range : float = 3.0;
function FixedUpdate () { var cols : Collider[] = Physics.OverlapSphere(transform.position, range); var rbs : Array = new Array(); for (c=0;c<cols.length;c++) { if (cols[c].attachedRigidbody && cols[c].attachedRigidbody != rigidbody) { var breaking :boolean = false; for (r=0;r<rbs.length;r++) { if (cols[c].attachedRigidbody == rbs[r]) { breaking=true; break; } } if (breaking) continue; rbs.Add(cols[c].attachedRigidbody); var offset : Vector3 = (transform.position - cols[c].transform.position); var mag: float = offset.magnitude; cols[c].attachedRigidbody.AddForce(offset/mag/mag * rigidbody.mass); }
} if(Input.GetButton("Jump")) rigidbody.mass = 50;
else rigidbody.mass = 5;
What I would like to add to this is the ability for the player to be able to press a button (for the sake of this I'm going to use "Fire1") and essentially reverse their gravity or push away the objects. I want it to just be like a quick burst and then have everything go back to normal. Is this possible with the script I have, or will I have to start over?
Answer by runevision · Oct 06, 2010 at 08:46 AM
Yes, that is easy to do with your existing script with just a tiny addition.
After this line:
var offset : Vector3 = (transform.position - cols[c].transform.position);
just add:
if (Input.GetButton("Fire1"))
offset = -offset;
This will reverse the force vector you are passing to the AddForce function.