Search Unity

Planetary Gravity and Movement

Discussion in 'Scripting' started by baconbot, Jan 7, 2014.

  1. baconbot

    baconbot

    Joined:
    Nov 26, 2013
    Posts:
    6
    Hello all. I've been wanting to make a game that takes place on a planet, and one that is actually a sphere. I've done a lot of searching and this is what I've come up with:

    Code (csharp):
    1. var gravity:float=-9.8;
    2.  
    3. function Update(){
    4.     rigidbody.velocity+=transform.position.normalized*gravity*Time.deltaTime;
    5.    
    6.     //simple movement
    7.     if(Input.GetKey('d')){
    8.         transform.localPosition.x+=0.1;
    9.     }
    10.     if(Input.GetKey('a')){
    11.         transform.localPosition.x-=0.1;
    12.     }
    13.     if(Input.GetKey('s')){
    14.         transform.localPosition.z-=0.1;
    15.     }
    16.     if(Input.GetKey('w')){
    17.         transform.localPosition.z+=0.1;
    18.     }
    19. }
    20.  
    21.  
    I have this script on a cube with the rigidbody component. This works okay(barely), but the result isn't really that smooth. The cube bounces around a lot, and usually flips a bunch, and ends up just orbiting the planet. Does anyone know how I could improve this, and make the player stay flat on the planet? (and I don't really care about jumping :) )

    Any suggestions would be greatly appreciated. Thanks
     
  2. MeowMixEater

    MeowMixEater

    Joined:
    Dec 23, 2013
    Posts:
    18
    If physics isn't needed for anything other than keeping the player on the planet you could lerp towards the planets transform until you hit its collider by raycasting towards the planet and and setting the point you are lerping towards as the hit point and set the bottom of the player object to always face the center of the planet. Not sure if I explained that well just an idea that might work well depending on what you are doing.
     
  3. baconbot

    baconbot

    Joined:
    Nov 26, 2013
    Posts:
    6
    Well I'm not sure I understand the first part, about the raycasting, but I think I get the whole facing the planet thing. I would have to do something with the normals of the planet I believe...