- Home /
Question by
unity_BRVDZdr0ShROPg · Jun 12, 2020 at 10:01 AM ·
rotationscripting problemphysicsrigidbodyadvice
Help making orbiting planets,How to rotate around the objects with the largest mass?
I'm trying to make a program that simulates space, I have gravity and attraction working, I'm trying to get orbiting working. The way I'm doing it is by finding the object causing the greatest effect on the planet, eg. The sun, but I don't want to just set it to rotate around a specific point, I want it to be an adaptive system, and help is appreciated
using System; using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine;
public class Attractor : MonoBehaviour {
const float G = 667.4f;
public float speed = 10f;
public static List<Attractor> Attractors;
public float forceMagnitude;
public Rigidbody rb;
Vector3 direction = new Vector3(0f,Mathf.Cos(-90),0f);
public float mass;
public int rotate;
public Vector3 nearestPlanet;
void FixedUpdate()
{
foreach (Attractor attractor in Attractors)
{
if (attractor != this)
Attract(attractor);
}
FindPlanet();
}
void OnEnable()
{
if (Attractors == null)
Attractors = new List<Attractor>();
Attractors.Add(this);
}
void OnDisable()
{
Attractors.Remove(this);
}
void Attract(Attractor objToAttract)
{
Rigidbody rbToAttract = objToAttract.rb;
Vector3 direction = rb.position - rbToAttract.position;
float distance = direction.magnitude;
if (distance == 0f)
return;
forceMagnitude = G * (rb.mass * rbToAttract.mass) / Mathf.Pow(distance, 2);
Vector3 force = direction.normalized * forceMagnitude;
rbToAttract.AddForce(force);
}
public Vector3 FindPlanet()
{
foreach (Attractor attractor in Attractors)
{
if (attractor != this)
{
mass = forceMagnitude;
int massInt = Convert.ToInt32(mass);
_ = new float[massInt];
rotate = Mathf.Max(massInt);
if (attractor.rb.mass == rotate && attractor != this)
{
nearestPlanet = attractor.transform.position;
}
//Debug.Log(nearestPlanet);
Orbit();
}
}
return nearestPlanet;
}
void Orbit()
{
transform.RotateAround(nearestPlanet, Vector3.up, speed * Time.deltaTime);
}
}
Comment