1
Fork 0
mirror of https://github.com/Steffo99/gravity-fusion.git synced 2024-11-29 03:24:30 +00:00
gravity-fusion/Assets/Components/Gravitation.cs

73 lines
2 KiB
C#
Raw Normal View History

2019-10-05 08:55:53 +00:00
using System.Collections;
using System.Collections.Generic;
2019-10-06 13:04:50 +00:00
using System.Linq;
2019-10-05 08:55:53 +00:00
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
{
2019-10-05 18:41:07 +00:00
[Header("Config")]
public bool isStatic;
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 09:48:36 +00:00
[Header("References")]
protected new Rigidbody2D rigidbody;
protected GameController gameController;
2019-10-05 08:55:53 +00:00
2019-10-06 17:04:47 +00:00
public List<Gravitation> SimulatedObjects {
get {
return gameController.simulatedObjects;
}
}
2019-10-05 18:41:07 +00:00
public float Mass {
2019-10-05 08:55:53 +00:00
get {
return rigidbody.mass;
}
2019-10-05 18:41:07 +00:00
}
2019-10-05 08:55:53 +00:00
2019-10-05 18:41:07 +00:00
public float GravitationConstant {
get {
return gameController.gravitationConstant;
2019-10-05 08:55:53 +00:00
}
}
2019-10-05 18:41:07 +00:00
private void Awake() {
rigidbody = GetComponent<Rigidbody2D>();
gameController = GameObject.Find("GameController").GetComponent<GameController>();
}
2019-10-05 10:36:09 +00:00
private void OnEnable() {
2019-10-06 17:04:47 +00:00
positionInList = SimulatedObjects.Count;
SimulatedObjects.Add(this);
2019-10-05 08:55:53 +00:00
}
2019-10-05 10:36:09 +00:00
private void OnDisable() {
2019-10-06 17:04:47 +00:00
SimulatedObjects.Remove(this);
2019-10-05 10:36:09 +00:00
}
2019-10-05 08:55:53 +00:00
private void Start()
{
appliedForce = new Vector3(0f, 0f, 0f);
}
// O(n²)
private void FixedUpdate()
{
2019-10-06 17:04:47 +00:00
foreach(Gravitation other in SimulatedObjects.Skip<Gravitation>(positionInList + 1)) {
2019-10-05 08:55:53 +00:00
if(other.positionInList <= this.positionInList) continue;
float distance = Vector3.Distance(this.transform.position, other.transform.position);
2019-10-05 21:50:43 +00:00
float force = GravitationConstant * this.Mass * other.Mass / Mathf.Clamp(Mathf.Pow(distance, 2), 0.1f, float.PositiveInfinity);
2019-10-05 08:55:53 +00:00
Vector3 direction = (other.transform.position - this.transform.position).normalized;
2019-10-05 18:41:07 +00:00
if(!this.isStatic) rigidbody.AddForce(direction * force);
if(!other.isStatic) other.rigidbody.AddForce(-direction * force);
2019-10-05 08:55:53 +00:00
}
appliedForce = new Vector3(0, 0, 0);
}
}