How do i make a Gravity for a 3D cube planet? I was trying to make a Gravity Area for every side, so if a gameobject enter a area the gravity will change. My idea was to do this with OntriggerEnter/Exit, but i´m trouble with the Code. Hope you can help me!
Lets say that you are using rigidbodies for physics. You could add the following script to any object that would be affected by physics;
//Following is C#, I can covert it to JS if you wish
using UnityEngine;
using System.Collections;
public class Gravity : MonoBehaviour
{
public Transform centreOfGravity; //The object to gravitate towards, in this case the cube
public float gravity = 1f; //The force of the gravity to be applied
public float maxDistance; //The maximum distance from the centreOfGravity this object can be whilst still being affected by gravity
private Rigidbody rb;
// Use FixedUpdate for physics calculations
void FixedUpdate ()
{
if (!GetComponent<Rigidbody>())
return; //If no rigidbody attached, return
if (Vector3.Distance (transform.position, centreOfGravity.position) > maxDistance)
return; //If we are further than the max distance, return
if (!rb)
rb = GetComponent.<Rigidbody>(); //If the rb variable is null, get the rigidbody attached to this object
if (rb.useGravity)
rb.useGravity = false; //Make sure the rigidbody isn't using the global gravity variable
Vector3 direction = (centreOfGravity.position - transform.position).normalized; //Get the direction of the cube and normalize so it doesn't have distance
RaycastHit hit; //Will contain information about the raycast we are about to perform
if (centreOfGravity.GetComponent<Collider>().Raycast (transform.position, direction, hit, maxDistance))
rb.AddForce (-hit.normal * gravity * rb.mass); //Apply the force to the rigidbody towards the relative surface of the cube. *note* that this will multiply the force by the rigidbody's mass so that all objects will fall at the same rate. If you don't want this, remove that section
}
}