I have this really annoying problem which I cannot seem to get to work, I am trying to make a planet, and have it so that my rigidbody character always has downwards gravity (already done) and is rotatating so that he always has the bottom side down (this seems to be the had part), any ideas? Thanks!
I created a rigidbody character which uses a local gravity that always points down to the surface it’s on. The character adjusts its position to be always perpendicular to the ground. Take a look at it in this answer - the question is Walking on walls, but the character can walk over spheric surfaces as well.
EDITED: My script really doesn’t work on a square planet - and may have problems in a spheric planet too, when the player is around the “south pole”. I’m studying this case and will be back as soon as I have some conclusion (your case is really complicated!)
Try this (C#):
using UnityEngine;
using System.Collections;
public class GravityScript : MonoBehaviour {
public Transform gravitySource;
public float gravScalar = 4.0f;
public Vector3 rotOffset = Vector3.zero;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
var direction = gravitySource.position - transform.position;
rigidbody.AddForce(direction.normalized * gravScalar);
transform.rotation = Quaternion.LookRotation(direction.normalized)
* Quaternion.Euler(rotOffset);
}
}
Just set up rotOffset so that the model looks like it should, and it should work. If you want a exponential gravity model, that is also easily possible with this.
Well, if your planets are cubes then it’s much easier to fake it. Just get the normal of the face you are currently on, and apply gravity in that direction! As for the rotation issue, try defining the axis of rotation and doing all your character rotations in terms of a rotation axis which is stored on the player. Every frame, interpolate it towards the current gravity direction, and that way the character will always stand up against their current “down”. To find out which is the closed floor, shoot out raycasts in all directions every few frames, and whichever one is the shortest is deemed to be the new “down”, and the gravity direction is set to the normal of the hit. This way, the character will always fall towards the nearest surface.