Created
April 23, 2020 13:05
-
-
Save saturngamesss/f609ce23ef389bea4a5949f7bbc3b69b to your computer and use it in GitHub Desktop.
Simple 2D planet gravity code for Unity Engine.
This file contains hidden or 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 | |
//************************************************ | |
// !!! Add this script to your object, NOT to the planet !!! | |
//************************************************ | |
using UnityEngine; | |
public class 2D_PlanetGravity : MonoBehaviour | |
{ | |
Rigidbody2D rb; | |
Vector2 lookDirection; | |
float lookAngle; | |
[Header ("Gravity")] | |
// Distance where gravity works | |
[Range(0.0f, 1000.0f)] | |
public float maxGravDist = 150.0f; | |
// Gravity force | |
[Range(0.0f, 1000.0f)] | |
public float maxGravity = 150.0f; | |
// Your planet | |
public GameObject planet; | |
void Start() | |
{ | |
rb = GetComponent<Rigidbody2D>(); | |
} | |
void Update() | |
{ | |
// Distance to the planet | |
float dist = Vector3.Distance(planet.transform.position, transform.position); | |
// Gravity | |
Vector3 v = planet.transform.position - transform.position; | |
rb.AddForce(v.normalized * (1.0f - dist / maxGravDist) * maxGravity); | |
// Rotating to the planet | |
lookDirection = planet.transform.position - transform.position; | |
lookAngle = Mathf.Atan2(lookDirection.y, lookDirection.x) * Mathf.Rad2Deg; | |
transform.rotation = Quaternion.Euler(0f, 0f, lookAngle); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment