Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Walking inside a sphere

Discussion in 'Editor & General Support' started by Borgstew, May 7, 2014.

  1. Borgstew

    Borgstew

    Joined:
    Sep 2, 2013
    Posts:
    1
    I'm trying to make a game that involves the player walking around the inside of a hollow sphere. Is there a way to make it so gravity is pulling from every edge to allow the player to walk on the walls and upside down, instead of just down?
     
  2. Iron-Warrior

    Iron-Warrior

    Joined:
    Nov 3, 2009
    Posts:
    838
    Yes. Take the direction from the player to the sphere, and then invert it. This will give you your gravity direction. Add a force to the player (depending on if you're using rigidbodies or what) in that direction. You'll probably also want to rotation the player to align his "feet" with the inside of the sphere. Here is a script I have that allows you to walk outside a sphere for a project I was working on...I'm not on my Unity machine so I can't really rewrite it to invert the direction but it should be easy enough, depending on your skill level. If you're not sure how feel free to ask!

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Gravity : MonoBehaviour {
    5.  
    6.     //credit some: podperson
    7.  
    8.     public Transform planet;
    9.     public bool AlignToPlanet;
    10.     private float gravityConstant = 9.8f;
    11.  
    12.     void Start () {
    13.        
    14.     }
    15.    
    16.     void FixedUpdate () {
    17.         Vector3 toCenter = planet.position - transform.position;
    18.         toCenter.Normalize();
    19.  
    20.         rigidbody.AddForce(toCenter * gravityConstant, ForceMode.Acceleration);
    21.  
    22.         if (AlignToPlanet)
    23.         {
    24.             Quaternion q = Quaternion.FromToRotation(transform.up, -toCenter);
    25.             q = q * transform.rotation;
    26.             transform.rotation = Quaternion.Slerp(transform.rotation, q, 1);
    27.         }
    28.     }
    29. }
    30.  
    Just a heads up though, Unity's character controller cannot be rotated, so you'll either have to use a rigidbody controller or be brave and program your own.
     
  3. Freddie404

    Freddie404

    Joined:
    Jan 20, 2019
    Posts:
    1
    How do I reverse that script so that the player remains inside the sphere and can walk around on the inside?