I have a system setup to try and detect when a player is in a specific planets gravity, but for some reason its not working. I will have my code below
I have empty game objects with mesh colliders and rigidbodys on them to emulate the atmosphere and when they enter a certain one, they need to be pulled in.
Here is the code i have: Thank you
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (Rigidbody))]
public class GravityBody : MonoBehaviour {
PlanetGravityEnter planet;
void Awake ()
{
planet = GameObject.FindGameObjectWithTag("Planet").GetComponentInChildren<PlanetGravityEnter>();
rigidbody.useGravity = false;
rigidbody.constraints = RigidbodyConstraints.FreezeRotation;
}
void FixedUpdate ()
{
planet.Attract (transform);
}
}
using UnityEngine;
using System.Collections;
public class PlanetGravityEnter : MonoBehaviour {
public float gravity = -10f;
public void OnTriggerStay (Collider body)
{
Attract (transform);
}
public void Attract(Transform body)
{
Vector3 targetDir = (body.position - transform.position).normalized;
Vector3 bodyUp = body.up;
body.rotation = Quaternion.FromToRotation (bodyUp, targetDir) * body.rotation;
body.rigidbody.AddForce (targetDir * gravity);
}
}
using UnityEngine;
using System.Collections;
public class FirstPersonController : MonoBehaviour {
public float mouseSensitivityX = 250f;
public float mouseSensitivityY = 250f;
public float walkSpeed;
public float runSpeed;
public float jumpForce;
public LayerMask groundedMask;
Transform cameraT;
float verticalLookRotation;
Vector3 moveAmount;
Vector3 smoothMoveVelocity;
bool grounded;
bool doubleJump = false;
void Start ()
{
Screen.showCursor = false;
cameraT = Camera.main.transform;
}
void Update ()
{
transform.Rotate (Vector3.up * Input.GetAxis ("Mouse X") * Time.deltaTime * mouseSensitivityX);
verticalLookRotation += Input.GetAxis("Mouse Y") * Time.deltaTime * mouseSensitivityY;
verticalLookRotation = Mathf.Clamp (verticalLookRotation, -80, 80);
cameraT.localEulerAngles = Vector3.left * verticalLookRotation;
Vector3 moveDir = new Vector3 (Input.GetAxisRaw ("Horizontal"), 0, Input.GetAxisRaw ("Vertical")).normalized;
Vector3 targetMoveAmount = moveDir * walkSpeed;
if (Input.GetKey(KeyCode.LeftShift) && grounded)
{
targetMoveAmount = moveDir * runSpeed;
}
moveAmount = Vector3.SmoothDamp (moveAmount, targetMoveAmount, ref smoothMoveVelocity, 0.15f);
if (Input.GetButtonDown ("Jump") && (grounded || !doubleJump)){
{
rigidbody.AddForce(transform.up * jumpForce);
if(!doubleJump && !grounded)
doubleJump = true;
}
}
if (grounded)
doubleJump = false;
grounded = false;
Ray ray = new Ray (transform.position, -transform.up);
RaycastHit hit;
if (Physics.Raycast (ray, out hit, 1 + 0.1f, groundedMask))
{
grounded = true;
}
}
void FixedUpdate()
{
rigidbody.MovePosition (rigidbody.position + transform.TransformDirection (moveAmount) * Time.fixedDeltaTime);
}
}