Search Unity

Faux Gravity making my brain spin... Help!

Discussion in 'Scripting' started by podperson, Feb 12, 2008.

  1. podperson

    podperson

    Joined:
    Jun 6, 2006
    Posts:
    1,370
    In the spirit of Mario Galaxy, I'm trying to replace the first person controller with a rigidbody that gravitates (and aligns) towards arbitrary objects.

    Here's what I've got so far (make a big sphere, stick something slightly above it, attach this script to it, and set its attractor to the sphere -- you should be able to zoom around on the sphere):

    Edit: the code posted here has been fixed -- see below. I've removed the guts of this post so that no-one inadvertently uses the old, highly borked code.

    Here's where I'd like help:

    Edit: note that these issues are all resolved in the code posted below.

    1) It's very hard to move without jumping if the terrain isn't smooth. How does the character controller overcome this without flying the rigidbody into space at rather slight provocations.

    2) This is subtler, but more annoying. I notice sometimes as I'm running around my little planet that my direction sometimes drifts slightly. But the WORST thing is that when I approach the south pole, I spin.

    My knowledge of Quaternions is pretty poor, so I'm obviously doing something wrong.

    3) I'd really prefer to adjust my up vector more gradually in the face of sudden changes of gravity (it's fine when the attractor doesn't change, obviously, but it will suck if I switch attractors suddenly as in a certain Wii game). I've been messing with Slerp but ... messing is the word and the result.

    (I also want to be able to fly a spaceship to a planet, and have it "snap into" the gravitational field and behave like a plane while close to the planet.)
     

    Attached Files:

  2. podperson

    podperson

    Joined:
    Jun 6, 2006
    Posts:
    1,370
    Edit: the code posted here has been fixed -- see below. I've removed the guts of this post so that no-one inadvertently uses the old, highly borked code.
     
  3. podperson

    podperson

    Joined:
    Jun 6, 2006
    Posts:
    1,370
    Another subtle issue.

    When I start gameplay my object (currently a capsule) is slightly above the landscape and it falls to the ground and slightly through it, then suddenly corrects itself and is fine thereafter. Jumping does not cause this issue (so if I jump afterwards, there's no problem.)

    Any ideas why?
     
  4. Doug

    Doug

    Joined:
    Oct 19, 2007
    Posts:
    36
  5. podperson

    podperson

    Joined:
    Jun 6, 2006
    Posts:
    1,370
    Actually I think my current code is probably less horrible than that ;-) But a neat idea.

    I believe my code will work fine for jumping between planets ... should have a demo soon.
     
  6. podperson

    podperson

    Joined:
    Jun 6, 2006
    Posts:
    1,370
    In case you're wondering ...

    I got all this working quite nicely, and then refactored it into:

    FauxGravityAttractor -- gizmo that exerts pull on objects; it resolves the pull and "upvector" stuff internally, so it could (theoretically) easily support non-spherical gravity (e.g. ring worlds, or local mono-directional gravity as seen in Mario Galaxy).

    FauxGravityBody -- objects that fall towards attractors. The simple version right now is that each body is only attached to one attractor at a time.

    FauxGravitySwitch -- objects that reassign objects to new attractors when a specific event (e.g. collision) occurs. The idea is to allow a spaceship fly up out of one planet's gravity-field ... into zero g ... and then enter another gravity-field.
     
  7. hai_ok

    hai_ok

    Joined:
    Jun 20, 2007
    Posts:
    193
    got it working!!!

    I love this! Thanks for your work on it!
    I'll be changing it heavily, but what you've done here will help me a LOT!!!

    most of the prefab camera scripts are -Y oriented, which breaks when you have a true orbital down direction.

    I'll be playing with the code to make a good third person camera.

    trouble is, that the only thing I got working was a cube collider, so it tumbles over the sphere like dice. Which is fun. he he

    I also made it ice, but then it just wouldn't stop. ha ha


    this is so cool, podperson!

    This is going to be a lot of fun to tinker with.
     
  8. hai_ok

    hai_ok

    Joined:
    Jun 20, 2007
    Posts:
    193
    ha ha ha!!!


    this is a GREAT simulator. the box got tumbling fast enough to reach orbit! sooooo cool!

    its still orbiting!

    oh! the ideas I'm getting now!!!!!!!
     
  9. marty

    marty

    Joined:
    Apr 27, 2005
    Posts:
    1,170
    Use a dummy-mediated camera, hai_ok.
     
  10. hai_ok

    hai_ok

    Joined:
    Jun 20, 2007
    Posts:
    193
    not sre what you mean, but I'm all ears.
     
  11. marty

    marty

    Joined:
    Apr 27, 2005
    Posts:
    1,170
    Attach a dummy (ie. empty game object) to the object that you want the camera to follow (ie. the player).

    Position the dummy so as to look at the player from the distance and angle desired when standing still.

    Program the camera to interpolate to the dummy's position, using a fractional interpolation (eg. 5% per interpolation) so as to get a nice bit of lag and easing.

    Works like a charm.
     
  12. hai_ok

    hai_ok

    Joined:
    Jun 20, 2007
    Posts:
    193
    I was thinking like that, but I hadn't got that together in my head just yet.

    you're right!

    child the null (dummy) to the player.
    mouse orbit the camera to the null.

    I could even child a target out in front of the player for the camera to look at, so that the camera is always looking toward what the player is facing.

    I know you are talking about doing this with code. I should try to think that way too.

    Thanks!
     
  13. jeffcraighead

    jeffcraighead

    Joined:
    Nov 15, 2006
    Posts:
    740
    podperson, can we see the new improved, refactored code please. :D

    Thanks!
     
  14. podperson

    podperson

    Joined:
    Jun 6, 2006
    Posts:
    1,370
    Here are my three gravity scripts -- hopefully self-documenting ;-)

    Basically, assign FauxGravityAttractor to each "planet" (or whatever) and assign FauxGravityBody to anything you want to move around on planets. I try to use the RigidBody properties where possible -- so it respects mass, and makes objects with freezeRotation set self-righting. (So set freezeRotation to true for characters, but false for random objects.)

    Note that I've got a "ground" layer set (10) for detecting whether an object is "grounded".

    Code (csharp):
    1.  
    2. /*
    3.     FauxGravityBody.js
    4.     Written by Tonio Loewald ©2008
    5.    
    6.     Attach this script to objects you want to be affected by FauxGravity
    7. */
    8.  
    9. // this is the thing we're gravitationally attracted to
    10. var attractor : FauxGravityAttractor;
    11.  
    12. // are we touching the surface?
    13. var grounded : int;
    14.  
    15. function Start () {
    16.     rigidbody.WakeUp();
    17.     rigidbody.useGravity = false;
    18. }
    19.  
    20. // obviously this is crude since we might want to be able to stand on (and jump off) random objects
    21. // should probably filter based on tag in future
    22. function OnCollisionEnter (c : Collision) {
    23.     if( c.gameObject.layer == 10 ){
    24.         grounded ++;
    25.     }
    26. }
    27.  
    28. function OnCollisionExit (c : Collision) {
    29.     if( c.gameObject.layer == 10  grounded > 0 ){
    30.         grounded --;
    31.     }
    32. }
    33.  
    34. function FixedUpdate () {
    35.     if(attractor){
    36.         attractor.Attract(this);
    37.     }
    38. }
    39.  
    40. @script RequireComponent(Rigidbody)
    41.  
    Code (csharp):
    1.  
    2. /*
    3.     FauxGravityAttractor.js
    4.     Written by Tonio Loewald ©2008
    5.    
    6.     Attach this script to objects you want to exert Faux Gravity
    7. */
    8.  
    9. // Set to true for mono-directional gravity
    10. var useLocalUpVector : boolean = false;
    11.  
    12. // Force applied along gravity up-vector (negative = down)
    13. var fauxGravity = -10.0;
    14.  
    15. function Attract ( body : FauxGravityBody ){
    16.     var gravityUp : Vector3;
    17.     var localUp: Vector3;
    18.     var localForward : Vector3;
    19.    
    20.     var t : Transform = body.transform;
    21.     var r : Rigidbody = body.rigidbody;
    22.  
    23.     // Figure out the body's up vector
    24.     if(useLocalUpVector){
    25.         gravityUp = transform.up;  
    26.     } else {
    27.         gravityUp = t.position - transform.position;
    28.         gravityUp.Normalize();
    29.     }
    30.    
    31.     // Accelerate the body along its up vector
    32.     r.AddForce( gravityUp * fauxGravity * r.mass );
    33.     r.drag = body.grounded ? 1 : 0.1;
    34.    
    35.     // If the object's freezerotation is set, we force the object upright
    36.     if(r.freezeRotation){
    37.         // Orient relatived to gravity
    38.         localUp = t.up;
    39.         var q = Quaternion.FromToRotation(localUp, gravityUp);
    40.         q = q * t.rotation;
    41.         t.rotation = Quaternion.Slerp(t.rotation, q, 0.1);
    42.         localForward = t.forward;
    43.     }
    44. }
    45.  
    Code (csharp):
    1.  
    2. /*
    3.     Faux Gravity Switch
    4.     Written by Tonio Loewald ©2008
    5.    
    6.     This is a simple example of a script which switches Faux Gravity attractors
    7. */
    8.  
    9. var OnEnterActive : boolean = false;
    10. var OnEnterSetAttractor : FauxGravityAttractor;
    11. var OnExitActive : boolean = false;
    12. var OnExitSetAttractor : FauxGravityAttractor;
    13.  
    14. function OnCollisionEnter( c : Collision ) {
    15.     if( OnEnterActive ){
    16.         var fg = c.gameObject.GetComponent(FauxGravityBody);
    17.         if( fg ){
    18.             fg.attractor = OnEnterSetAttractor;
    19.         }
    20.     }
    21. }
    22.  
    23. function OnCollisionExit( c : Collision ) {
    24.     if( OnExitActive ){
    25.         var fg = c.gameObject.GetComponent(FauxGravityBody);
    26.         if( fg ){
    27.             fg.attractor = OnExitSetAttractor;
    28.         }
    29.     }
    30. }
    31.  
     
  15. jeffcraighead

    jeffcraighead

    Joined:
    Nov 15, 2006
    Posts:
    740
  16. podperson

    podperson

    Joined:
    Jun 6, 2006
    Posts:
    1,370
    Obviously for a more realistic simulation gravity would decrease with distance via the inverse square law, and for even more realism, everything would be attracted to everything else ... but this works very nicely for game play (and it's not like the built-in gravity is realistic in this way)
     
  17. AaronC

    AaronC

    Joined:
    Mar 6, 2006
    Posts:
    3,544
    Is this close?
    AC
     

    Attached Files:

  18. Obscurity

    Obscurity

    Joined:
    Nov 13, 2007
    Posts:
    203
  19. marty

    marty

    Joined:
    Apr 27, 2005
    Posts:
    1,170
    I developed a game in Shockwave3D that does this after noodling with it for a couple of years. I used more or less the same approach, buttressed with some raycasting trickery.

    You can see that game right now at http://gigaplay.com/microbop

    In fact, I'm working on a Unity game right now that uses the same approach, only to much better effect, thanks to Unity's being about a gazillion times better than Director Shockwave. I should have some demos ready to post soon.
     
  20. Obscurity

    Obscurity

    Joined:
    Nov 13, 2007
    Posts:
    203
    Marty, that's really cool. And definitely impressive given the limitations of Shockwave. Looking forward to your Unity implementation.
     
  21. podperson

    podperson

    Joined:
    Jun 6, 2006
    Posts:
    1,370
    I considered using surface normals to determine the gravity vector, but I wasn't planning on using smooth irregular shapes for attractors (as Super Mario Galaxy does) ... and doing so entails keeping track of which things are attractors and which aren't, so you don't inadvertently walk on the sides of walls. Also, normally you don't want your up vector to change when you walk up a hill.

    For any actual game you'd probably end up using a whole bunch of different attractors to handle edge cases.
     
  22. atholm

    atholm

    Joined:
    Oct 10, 2008
    Posts:
    28
    Hi Podperson
    Really enjoying your script.. very nice!

    I'm having trouble with trying to make a simple character move on the object..
    When assigning a character controller it simply won't move :)

    Maybe the character controller has fixed gravity?
     
  23. podperson

    podperson

    Joined:
    Jun 6, 2006
    Posts:
    1,370
    Yeah, you need to give up on the character controller unfortunately.

    On the positive side, the only thing you really get out of the character controller is the "grounded" business, which the faux gravity scripts take care of for you.
     
  24. atholm

    atholm

    Joined:
    Oct 10, 2008
    Posts:
    28
    Ahh I see... Thanks you :)
    It is hard to move the character without it tumbles around like mad :)

    But quite funny :)
     
  25. podperson

    podperson

    Joined:
    Jun 6, 2006
    Posts:
    1,370
    If you use a rigidbody and lockrotation then the faux gravity body script will keep your feet pointed "down".
     
  26. atholm

    atholm

    Joined:
    Oct 10, 2008
    Posts:
    28
    Nice thank you.. haven't seen the freeze rotation parameter :)
     
  27. dock

    dock

    Joined:
    Jan 2, 2008
    Posts:
    376
    Podperson - this script is fantastic, very nice work and very clean code to boot. Thank-you for sharing this!
     
  28. cyb3rmaniak

    cyb3rmaniak

    Joined:
    Dec 10, 2007
    Posts:
    162
    Awesome work!

    I was thinking about doing something like for quite a while now, and didn't have the time.

    Good job!
     
  29. melmonkey

    melmonkey

    Joined:
    Mar 31, 2009
    Posts:
    373
    I have been messing with these scripts, and I am running into an issue. Hopefully someone else has bumped up against this, and has the solution.

    I have a simple scene with a Unity sphere for the planet, and the Unity capsule for the character.

    When I walk away from the poles of the sphere towards the equator, the cylinder starts getting all jumpy and slows way down until I get to the actual equator, at which point it stops responding to any input.

    I down loaded the unity package in the thread, and dropped the rigidbody controller script on the capsule, and while this works a little better, when I cross the equator my capsule blasts off into space.

    Can anyone duplicate my results, or have a set of steps to take to get this to work? This is just for testing/prototyping purposes right now, so using the default assets in unity is great.
     
  30. melmonkey

    melmonkey

    Joined:
    Mar 31, 2009
    Posts:
    373
    One bump and then I start a new topic.
     
  31. Eggpoacher

    Eggpoacher

    Joined:
    Nov 23, 2009
    Posts:
    9
    OK! Say I have, "A Friend", who is a great artist but has 0 programming skills, who is creating just this almost exact same thing, but does not know how to get that bit of code from this forum to his planet in Unity.

    Scoop it up, plop it here, and GO!

    I do, I mean, He does, however understand how to set up the camera now. Thanks!


    PS- I did get the file posted earlier in the thread into unity but im not sure what to add where... I just need pointed in the right direction then I can figure out the kinks.

    Yeah I'm missing something. I could make it work with the project file that it came with but I can't make it work for my assets. Somethings not going right...
     
  32. KHopcraft

    KHopcraft

    Joined:
    Jun 6, 2009
    Posts:
    3,246
    Really sorry to bump this old topic but...

    How do you make it so you can have multiple planets?
    So the objects are affected by both.
     
  33. KHopcraft

    KHopcraft

    Joined:
    Jun 6, 2009
    Posts:
    3,246
  34. techmage

    techmage

    Joined:
    Oct 31, 2009
    Posts:
    2,067
    I made some edits to the faux gravity scripts if anyone else needs them.

    The first one adds a fadeout radius to the gravities pull, with gizmos to show you the fade.

    Code (csharp):
    1. /*
    2.    FauxGravityAttractor.js
    3.    Written by Tonio Loewald ©2008
    4.    
    5.    Attach this script to objects you want to exert Faux Gravity
    6. */
    7.  
    8. // Force applied along gravity up-vector (negative = down)
    9. var fauxGravity = -10.0;
    10.  
    11. //everything within this radius is pulled towards the center at a constant rate in all areas
    12. var gravityRadius : float;
    13.  
    14. //gravityRadius will fade out to zero pull by the time it reaches this radius ( make bigger than gravityRadius)
    15. var gravityRadiusFade : float;
    16.  
    17. //makes the gravityRadius's proportionate to the objects scale
    18. var RadiiProportionateToScale : boolean = true;
    19.  
    20. //controls ratio of gravityRadius var to the objects scale
    21. var radiusProportion : float = .75;
    22.  
    23. //controls ratio of gravityRadiusFade var to the objects scale
    24. var radiusFadeProportion : float = 1.5;
    25.  
    26. function Attract ( body : FauxGravityBody ){
    27.  
    28.    var gravityUp : Vector3;
    29.    var localUp: Vector3;
    30.    var localForward : Vector3;
    31.    
    32.    var t : Transform = body.transform;
    33.    var r : Rigidbody = body.rigidbody;
    34.    
    35.     var shipDistance : float = Vector3.Distance(transform.position, body.transform.position);
    36.  
    37.    // Figure out the body's up vector
    38.     gravityUp = t.position - transform.position;
    39.     gravityUp.Normalize();
    40.      
    41.     gravityRadius = transform.localScale.x * .75;
    42.     gravityRadiusFade = transform.localScale.x * 1.5;
    43.      
    44.      
    45.     // Accelerate the body along its up vector 
    46.     if (shipDistance < gravityRadius)
    47.     {  
    48.         r.AddForce(gravityUp * fauxGravity);
    49.     }
    50.     else if ( shipDistance > gravityRadius  shipDistance < gravityRadiusFade)
    51.     {
    52.         //percentage of position inbetween radius
    53.         r.AddForce(gravityUp * (fauxGravity * (1 -(shipDistance - gravityRadius) / (gravityRadiusFade - gravityRadius))));
    54.     }
    55.        
    56.    if (body.grounded){
    57.         r.drag = 0;
    58.     }
    59.  
    60. }
    61.  
    62.  
    63. function OnDrawGizmos () {
    64.  
    65.     if (RadiiProportionateToScale)
    66.     {
    67.         gravityRadius = transform.localScale.x * radiusProportion;
    68.         gravityRadiusFade = transform.localScale.x * radiusFadeProportion;
    69.     }
    70.    
    71.     Gizmos.color = Color.white;
    72.    
    73.     Gizmos.DrawWireSphere(transform.position, gravityRadius);
    74.     Gizmos.DrawWireSphere(transform.position, gravityRadiusFade);
    75. }
    The second one lets you put multiple fauxGravityAttractors onto one fauxGravityBody

    Code (csharp):
    1. /*
    2.    FauxGravityBody.js
    3.    Written by Tonio Loewald ©2008
    4.    
    5.    Attach this script to objects you want to be affected by FauxGravity
    6. */
    7.  
    8. // this is the thing we're gravitationally attracted to
    9. var attractor : FauxGravityAttractor[];
    10.  
    11. // are we touching the surface?
    12. var grounded : int;
    13.  
    14. var attract : boolean = true;
    15.  
    16. function Start () {
    17.    rigidbody.WakeUp();
    18.    rigidbody.useGravity = false;
    19. }
    20.  
    21. // obviously this is crude since we might want to be able to stand on (and jump off) random objects
    22. // should probably filter based on tag in future
    23. function OnCollisionEnter (c : Collision) {
    24.    if( c.gameObject.layer == 10 ){
    25.       grounded ++;
    26.    }
    27. }
    28.  
    29. function OnCollisionExit (c : Collision) {
    30.    if( c.gameObject.layer == 10  grounded > 0 ){
    31.       grounded --;
    32.    }
    33. }
    34.  
    35. function FixedUpdate () {
    36.  
    37.     if (attract)
    38.     {
    39.         for ( i=0; i < attractor.length; i++){
    40.    
    41.             if(attractor[i]){
    42.                 attractor[i].Attract(this);
    43.             }
    44.         }
    45.     }
    46.    
    47. }
    48.  
    49. @script RequireComponent(Rigidbody)
     
  35. KHopcraft

    KHopcraft

    Joined:
    Jun 6, 2009
    Posts:
    3,246
    THANKS.

    Thanks a lot. You made the beginning of the year amazing.
     
  36. yesimarobot

    yesimarobot

    Joined:
    Jun 19, 2009
    Posts:
    24
    How would you go about adding the ability to jump to the game objects in orbit?
     
  37. Broken-Toy

    Broken-Toy

    Joined:
    Jan 16, 2010
    Posts:
    455
    Thanks a lot for this script, it's going to inspire me a lot as the core of a project of mine.

    One thing that I started to notice since switching gravity is the amount of standard scripts that rely on the arbitrary world axis as a "lazy shortcut" instead of each object's local axis system (not blaming anyone, why do otherwise in a world with a single known gravity direction?). These scripts have to be re-written to take the new local gravity vector as a Y axis, notably for movement and cameras.

    One big helper is to "snap" the object's local Y axis along the gravity vector. I thought I'd share the few lines for those still looking for them. I also noticed that multiple gravity sources always kept the same radius, so went and fixed that part as well.

    In FauxGravityBody.js add this public var at the top:
    Code (csharp):
    1.    var snapYaxisToGravity: boolean = false;
    In FauxGravityAttractor.js replace the four lines of code right after the comment "Figure out the body's up vector":
    Code (csharp):
    1.    // Figure out the body's up vector
    2.    gravityUp = t.position - transform.position;
    3.    gravityUp.Normalize();
    4.      
    5.    gravityRadius = transform.localScale.x * 0.75;
    6.    gravityRadiusFade = transform.localScale.x * 1.5;
    With this (adds snapping and fixes radii not updating):
    Code (csharp):
    1.    // Figure out the body's up vector
    2.    gravityUp = t.position - transform.position;
    3.    gravityUp.Normalize();
    4.      
    5.    gravityRadius = transform.localScale.x * radiusProportion;
    6.    gravityRadiusFade = transform.localScale.x * radiusFadeProportion;
    7.  
    8.    // Snap to the body's up vector if enabled on body (toggle).
    9. if (body.snapYaxisToGravity == true)
    10.    {
    11.       if (r.freezeRotation != true) r.freezeRotation = true;
    12.       body.transform.rotation = Quaternion.FromToRotation (Vector3.up, gravityUp);
    13.    }
    14.     else if (r.freezeRotation != false) r.freezeRotation = false;
    From then on, you can reliably reference an object's local axis for your movement and camera needs when snapping it to the local gravity when needed. For cameras, I currently have some issues with the orbiting script; yes, I can make the camera face the right direction and rotation, but I can't get it to orbit around the target's Y axis (it insists on using the world's Y axis).
     
  38. Daev-Finn

    Daev-Finn

    Joined:
    Dec 12, 2009
    Posts:
    145
    I'm a late entry into this discussion, examining methods of changing gravity in my game.

    I am developing for the iPhone and have created the FauxGravity scripts as suggested in these posts, however I get errors and don't see the scripts in my drop down of scripts. It also seems to suddenly block most of my scripts from being processed when I create these.

    Is this something that has been tested on the iPhone? Any thoughts about what I may be doing wrong?

    The error I get: 'attractor' is not a member of 'UnityEngine.Compnent'
     
  39. forgottenmindset

    forgottenmindset

    Joined:
    Dec 3, 2009
    Posts:
    72

    Hey man, I love your version of the code, I'm having my little guy sling between planets, but the only problem is it doesn't self right the gravity body, I added a snipped of self righting code from the original code and it works for 1 planet, but if 2 or 3 planets are attracting a body, it gets confused and self rights in a strange way.

    How can I make it self right to the current planet?
     
  40. Ka Ora!

    Ka Ora!

    Joined:
    Mar 11, 2010
    Posts:
    7
    I have run up against the same issue as melmonkey, In that when the capsule gets to the equator it falls off?

    I have included the scene. I someone could point out were im going wrong please.

    cheers
     

    Attached Files:

  41. Ka Ora!

    Ka Ora!

    Joined:
    Mar 11, 2010
    Posts:
    7
    Can anyone help at all? Im baffled as to why it falls off at the equator all the time.

    Thanks
     
  42. pickledzebra

    pickledzebra

    Joined:
    Feb 25, 2010
    Posts:
    33
    None of these scripts appear to work as intended. The player object always falls of the sphere. :(
     
  43. Ka Ora!

    Ka Ora!

    Joined:
    Mar 11, 2010
    Posts:
    7
    I could never get it to work, Unity is set up with Single direction Gravity. And support said to me that PhysX Assumes Terrain is flat. What im trying to implement as a work around is have the Spherical Terrain mesh rotate under the FPS.
     
  44. joehamilton

    joehamilton

    Joined:
    Apr 24, 2010
    Posts:
    10
    I'm having trouble getting these scripts working. :?

    Has anyone got a working version of this they would be willing to share?

    Thanks :)
     
  45. Roachie

    Roachie

    Joined:
    Aug 2, 2009
    Posts:
    64
    Bump.

    Any one ever get this working ? my object always falls off the world when getting to the bottum of the sphere
     
  46. Sbach

    Sbach

    Joined:
    May 18, 2010
    Posts:
    9
    You can try my first unity script:

    Code (csharp):
    1.  
    2. var fauxGravity = -10.0;
    3. var gravityRadius : float;
    4. var gravityRadiusFade : float;
    5. var RadiiProportionateToScale : boolean = true;
    6. var radiusProportion : float = .75;
    7. var radiusFadeProportion : float = 1.5;
    8. var actualforce : Vector3;
    9. var myStyle : GUISkin;
    10. var gravityUp : Vector3;
    11.  
    12. function FixedUpdate ()
    13. {
    14.     if (RadiiProportionateToScale)
    15.     {
    16.         gravityRadius = transform.localScale.x * radiusProportion;
    17.         gravityRadiusFade = transform.localScale.x * radiusFadeProportion;
    18.     }
    19.    
    20.     var cols : Collider[] = Physics.OverlapSphere(transform.position, gravityRadiusFade);
    21.     var rbs : Array = new Array();
    22.     for (c=0;c<cols.length;c++)
    23.     {
    24.         if (cols[c].attachedRigidbody  cols[c].attachedRigidbody != rigidbody)
    25.         {
    26.             var breaking :boolean = false;
    27.             for (r=0;r<rbs.length;r++)
    28.             {
    29.                 if (cols[c].attachedRigidbody == rbs[r])
    30.                 {
    31.                     breaking=true;
    32.                     break;
    33.                 }
    34.             }
    35.             if (breaking){continue;}
    36.            
    37.             rbs.Add(cols[c].attachedRigidbody);
    38.            
    39.             var shipDistance : float = Vector3.Distance(transform.position, cols[c].transform.position);
    40.  
    41.             gravityUp = cols[c].transform.position - transform.position;
    42.             gravityUp.Normalize();
    43.            
    44.             cols[c].transform.rotation = Quaternion.FromToRotation (Vector3.up, gravityUp);
    45.            
    46.             if (shipDistance < gravityRadius)
    47.             {
    48.                 actualforce = gravityUp * fauxGravity;
    49.                 cols[c].attachedRigidbody.AddForce(actualforce);
    50.                 cols[c].attachedRigidbody.drag=10;
    51.             }
    52.             else if ( shipDistance > gravityRadius  shipDistance < gravityRadiusFade)
    53.             {
    54.                 actualforce = gravityUp * (fauxGravity * (1 -(shipDistance - gravityRadius) / (gravityRadiusFade - gravityRadius)));
    55.                 cols[c].attachedRigidbody.AddForce(actualforce);
    56.             }
    57.         }
    58.     }
    59. }
    60.  
    61. function OnGUI () {
    62.     GUI.skin =myStyle;
    63.     GUI.Box (Rect (0,0,240,20), actualforce.ToString());
    64.     GUI.Box (Rect (0,20,240,20), gravityUp.ToString());
    65. }
    66. function OnDrawGizmos () {
    67.  
    68.    if (RadiiProportionateToScale)
    69.    {
    70.       gravityRadius = transform.localScale.x * radiusProportion;
    71.       gravityRadiusFade = transform.localScale.x * radiusFadeProportion;
    72.    }
    73.    
    74.    Gizmos.color = Color.white;
    75.    
    76.    Gizmos.DrawWireSphere(transform.position, gravityRadius);
    77.    Gizmos.DrawWireSphere(transform.position, gravityRadiusFade);
    78. }
    79.  
    This script is a mod of the previous scripts.
    Attach it to a sphere and all rigidbodys around will be attracted.
     
  47. KHopcraft

    KHopcraft

    Joined:
    Jun 6, 2009
    Posts:
    3,246
    That is also your first post, welcome to the forums :D.

    Thanks for the script :).
     
  48. Daellus

    Daellus

    Joined:
    Jul 14, 2010
    Posts:
    1
    I was just about to post and ask.
    Tuesday I got the old code (from an
    older post, methinks) and after
    much of the borkness got it to work.
    my poor Lerpz gets a head rush and his
    head explodes everytime he tries to
    leave the bottom of the spheroid. :)

    I have a related question though. My
    goal is to use a Toroid as my world-space.
    (A cross between a fps/race/galaga style
    tube-runner game with overtones of unreal
    and ringworld).

    Ideas? The biggest problem i see coming up
    is that i'll need to be able to merge the
    player THROUGH the surface of the torus. So
    the gameplay will be inside AND outside the
    tube.

    The Gravity is just the start of the headaches.
    But the most important part. Especially since
    my destination world-space is to be a wormhole
    style tube that twists many such ways.
     
  49. trancerobot

    trancerobot

    Joined:
    Jul 18, 2010
    Posts:
    69
    Neat work podperson, I've just finished something similar.

    To have everything attracted to everything else, you can make this script a trigger, and attach it to a Sphere Collider with IsTrigger enabled and no Mesh Renderer. Then you can parent the newly created gravity trigger to a Rigidbody object.
     
  50. Mangopork

    Mangopork

    Joined:
    Aug 16, 2009
    Posts:
    108
    Sweeeeeeeeeeet.

    Are you going to make a full game with this or are you just tinkering?