2019-10-05 08:55:53 +00:00
|
|
|
|
using System.Collections;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using UnityEngine;
|
|
|
|
|
|
2019-10-05 09:48:36 +00:00
|
|
|
|
[RequireComponent(typeof(Rigidbody2D))]
|
2019-10-05 08:55:53 +00:00
|
|
|
|
public class Gravitation : MonoBehaviour
|
2019-10-05 09:48:36 +00:00
|
|
|
|
{
|
|
|
|
|
[Header("Forces")]
|
|
|
|
|
protected Vector3 appliedForce;
|
2019-10-05 08:55:53 +00:00
|
|
|
|
|
2019-10-05 09:48:36 +00:00
|
|
|
|
[Header("Internals")]
|
2019-10-05 08:55:53 +00:00
|
|
|
|
public int positionInList;
|
2019-10-05 10:36:09 +00:00
|
|
|
|
public static List<Gravitation> simulatedObjects;
|
2019-10-05 08:55:53 +00:00
|
|
|
|
|
2019-10-05 09:48:36 +00:00
|
|
|
|
[Header("References")]
|
|
|
|
|
protected new Rigidbody2D rigidbody;
|
|
|
|
|
protected GameController gameController;
|
2019-10-05 08:55:53 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
protected float mass {
|
|
|
|
|
get {
|
|
|
|
|
return rigidbody.mass;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
set {
|
|
|
|
|
rigidbody.mass = value;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-05 10:36:09 +00:00
|
|
|
|
private void OnEnable() {
|
2019-10-05 08:55:53 +00:00
|
|
|
|
if(simulatedObjects == null) {
|
|
|
|
|
simulatedObjects = new List<Gravitation>();
|
|
|
|
|
}
|
|
|
|
|
positionInList = simulatedObjects.Count;
|
|
|
|
|
simulatedObjects.Add(this);
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-05 10:36:09 +00:00
|
|
|
|
private void OnDisable() {
|
|
|
|
|
simulatedObjects.Remove(this);
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-05 08:55:53 +00:00
|
|
|
|
private void Start()
|
|
|
|
|
{
|
|
|
|
|
rigidbody = GetComponent<Rigidbody2D>();
|
|
|
|
|
gameController = GameObject.Find("GameController").GetComponent<GameController>();
|
|
|
|
|
appliedForce = new Vector3(0f, 0f, 0f);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// O(n²)
|
|
|
|
|
private void FixedUpdate()
|
|
|
|
|
{
|
|
|
|
|
foreach(Gravitation other in simulatedObjects) {
|
|
|
|
|
if(other.positionInList <= this.positionInList) continue;
|
|
|
|
|
float distance = Vector3.Distance(this.transform.position, other.transform.position);
|
|
|
|
|
float force = gameController.gravitationConstant * this.mass * other.mass / Mathf.Pow(distance, 2);
|
|
|
|
|
Vector3 direction = (other.transform.position - this.transform.position).normalized;
|
|
|
|
|
this.appliedForce += direction * force;
|
|
|
|
|
other.appliedForce -= direction * force;
|
|
|
|
|
}
|
|
|
|
|
rigidbody.AddForce(appliedForce);
|
|
|
|
|
appliedForce = new Vector3(0, 0, 0);
|
|
|
|
|
}
|
|
|
|
|
}
|