Hey all, trying to create a sort of faux gravity that will allow my player character to walk around a 3D sphere (like a small planet). Currently, whenever play the scene the player character flies away from the planet as opposed to being attracted to it and I can’t seem to figure out why.
This script goes on the player character, who has a Rigidbody with gravity off:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FauxGravityBody : MonoBehaviour
{
public FauxGravityAttractor attractor;
private Transform myTransform;
void Start()
{
GetComponent<Rigidbody>().constraints = RigidbodyConstraints.FreezeRotation;
GetComponent<Rigidbody>().useGravity = false;
myTransform = transform;
}
void Update()
{
attractor.Attract(myTransform);
}
}
And this code is set on the planet:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FauxGravityAttractor : 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);
}
}
Any idea what I’m doing wrong here? As I understand it the planet should have an attractive force on the player character, but instead I have a repulsive force (that is admittedly sending it flying hilariously fast away)