Trying to simulate plant to sun orbit

I’m trying to simulate the type of orbit that real planets make which uses gravitational force but Im trying to make the planet have its own force which strays away from the sun but it starts to orbit but then it gets pulled in by the gravitational force of the sun, and when I try to increase the amount of force the planet is exerting on its own it overwhelms the gravitational force

2 Likes

This post might help you.

The thing is the way he is doing it is simulated, and I wanted it to start to orbit on its own accord like in the real universe but this is probably the closest Ill get so thanks

1 Like

Not a direct solution to your code, but I think you can use LineForce for this instead of a RunService.Heartbeat loop, which would probably be a bit easier on performance. You would enable LineForce.InverseSquareLaw and the math will have some minor changes. You might also have to disable gravity in Workspace if you haven’t already.

2 Likes

I have achieved a simple orbit example with LineForce, video gif here: https://i.gyazo.com/2dbe4d45ea8a3e0a80e79ceedc3541eb.mp4

The complete code for this is:

--earth orbiting the sun
local sun = workspace:FindFirstChild("Sun")
local earth = workspace:FindFirstChild("Earth")

local G = 6.67*10 --gravitational constant
--this is what I found worked good with my sizing, you can modify it

--must be no workspace gravity, and the bodies have to unanchored
workspace.Gravity = 0
earth.Anchored = false
sun.Anchored = false

local earthAttachment = Instance.new("Attachment", earth)
local sunAttachment = Instance.new("Attachment", sun)

local lineForce = Instance.new("LineForce", earth)
lineForce.InverseSquareLaw = true
lineForce.Attachment0 = earthAttachment
lineForce.Attachment1 = sunAttachment

--from newton's gravitational formula (minus divide by r^2)
--don't need the divide because LineForce.InverseSquareLaw handles that
lineForce.Magnitude = G * sun.AssemblyMass * earth.AssemblyMass

--apply some perpendicular velocity so the planet doesn't just go straight into the sun lol
earth:ApplyImpulse(Vector3.new(0, 0, 150))

You will need to adjust both the ApplyImpulse line values and local G to your situation. There is most likely a way to actually calculate the velocity needed by ApplyImpulse to send the body into a specific orbit.

1 Like

Maybe part of your problem is this—planets don’t have any forces on them other than gravity. They have some initial velocity sideways that keeps them from hitting the other object as they fall. The only force on them is gravity.

1 Like