Last active
April 22, 2020 18:03
-
-
Save saturngamesss/2a54b9f22deee88ef49b0b1a84a784f8 to your computer and use it in GitHub Desktop.
Planet gravity code for Unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//************** REAL GAMES STUDIO *************** | |
//************************************************ | |
//realgamesss.weebly.com | |
//gamejolt.com/@Real_Game | |
//realgamesss.newgrounds.com/ | |
//real-games.itch.io/ | |
//youtube.com/channel/UC_Adg-mo-IPg6uLacuQCZCQ | |
//************************************************ | |
using UnityEngine; | |
using System.Collections; | |
public class GravityAttractor : MonoBehaviour { | |
public float gravity = -9.8f; | |
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//************** REAL GAMES STUDIO *************** | |
//************************************************ | |
//realgamesss.weebly.com | |
//gamejolt.com/@Real_Game | |
//realgamesss.newgrounds.com/ | |
//real-games.itch.io/ | |
//youtube.com/channel/UC_Adg-mo-IPg6uLacuQCZCQ | |
//************************************************ | |
using UnityEngine; | |
using System.Collections; | |
[RequireComponent (typeof (Rigidbody))] | |
public class GravityBody : MonoBehaviour { | |
GravityAttractor planet; | |
Rigidbody rigidbody; | |
void Awake () { | |
planet = GameObject.FindGameObjectWithTag("Planet").GetComponent<GravityAttractor>(); | |
rigidbody = GetComponent<Rigidbody> (); | |
// Disable rigidbody gravity and rotation as this is simulated in GravityAttractor script | |
rigidbody.useGravity = false; | |
rigidbody.constraints = RigidbodyConstraints.FreezeRotation; | |
} | |
void FixedUpdate () { | |
// Allow this body to be influenced by planet's gravity | |
planet.Attract(rigidbody); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment