I've implemented faux gravity by attaching the below Gravity Attractor script to a sphere object, and the Gravity Body script to my player. This works fine for moving around the surface of the sphere as if it were a planet, attracting the player to the center.
However I now want to implement the same effect on a cylinder instead of a sphere, so that the player can move around the cylinder and up and down the long side as they wish. Right now the faux gravity is pulling the player towards the center of the cylinder because that's the center of the rigid body.
How could I change this so the player is instead just pulled to the inside of the cylinder, not the center of the inside?
public class GravityAttractor : MonoBehaviour {
public float gravity = -10;
public void Attract(Transform body){
Vector3 gravityUp = (body.position - transform.position).normalized;
Vector3 bodyUp = body.up;
body.GetComponent<Rigidbody>().AddForce(gravityUp * gravity);
Quaternion targetRotation = Quaternion.FromToRotation(bodyUp, gravityUp) * body.rotation;
body.rotation = Quaternion.Slerp(body.rotation, targetRotation, 50 * Time.deltaTime);
}
}
public class GravityBody : MonoBehaviour {
public GravityAttractor attractor;
private Transform myTransform;
void Start () {
Rigidbody body = GetComponent<Rigidbody>();
body.freezeRotation = true;
body.useGravity = false;
myTransform = transform;
}
void Update () {
attractor.Attract(myTransform);
}
}