Help with 1 script on 2 objects
So I have this script that gives spherical planets gravity that a player can walk on. It works great when only one planet is in the scene that has this script attached to it, but when I attach this script to more than one planet in the scene, it gets all wonky. The rotation of the player to the surface normals doesn't work anymore, and when I enter the other planet's gravity radius, the gravity doesn't work at all. I have no idea what is going on, since I had this working just fine earlier today. I'm not even sure that I changed anything at all from then, so any help is really appreciated. Please get back to me asap. Here is the script:
using UnityEngine; using System.Collections;
public class GravityAttractor : MonoBehaviour { //GravityAttractor planet; public float gravity = -9.8f; public float gravityRadius = 10.0f; public Color gizmosColor = Color.red; public Transform playerTarget; public GameObject player; Rigidbody rigidbody;
void Awake() { rigidbody = player.GetComponent();
// Disable rigidbody gravity and rotation as this is simulated in GravityAttractor script
rigidbody.useGravity = false;
rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
}
public void Attract(Rigidbody body) { Vector3 gravityUp = (body.position - transform.position).normalized; Vector3 localUp = body.transform.up;
// Apply downwards gravity to body
body.AddForce(gravityUp * gravity);
// Allign bodies up axis with the centre of planet
body.rotation = Quaternion.FromToRotation(localUp, gravityUp) * body.rotation;
}
void FixedUpdate() { float distance = Vector3.Distance( playerTarget.position, this.transform.position);
if (distance < gravityRadius)
{
Attract(rigidbody);
player.transform.SetParent(this.transform);
}
if(distance > gravityRadius)
{
player.transform.parent = null;
}
}
void OnDrawGizmos() { Gizmos.color = gizmosColor; Gizmos.DrawWireSphere(transform.position, gravityRadius); }
}