On integrating a physical trajectory before simulation
Hi!
I have super simple project with only two game objects, both of them spheres with rigidbodies. One of them is fixed and the other can move, it starts at a certain distance from the fixed one and with an initial velocity, and in the update it has a force towards the other object (at this point I might just say, think of two planets orbiting).
The force update is as follows
Vector3 gravVect = sun.GetComponent<Rigidbody>().position-rigidBody.position;
float distance = gravVect.magnitude;
float mass = rigidBody.mass;
gravVect.Normalize();
rigidBody.AddForce(mass*gravVect/(distance*distance));
This is in the smaller planet script.
Now this works fine, and if a put an Effects/Trail as a child to this last object, it properly displays a fixed ellipse.
The problem is that I want the code to calculate the trajectory and display it as a line before the object moves. There is an Effects/Line as a child of this game object, and this same script does this calculation with the following code, which is just a Euler step integration of the equation of motion:
void DrawLine()
{
Vector3 currentSpeed = rigidBody.velocity;
Vector3 intSpeed = currentSpeed;
Vector3 currentPosit = rigidBody.position;
Vector3 intPosit = currentPosit;
Vector3 gravVect = sun.GetComponent<Rigidbody>().position-currentSpeed;
float distance = gravVect.magnitude;
float dT = Time.fixedDeltaTime;
for (int i = 0; i < pointsInteg; i++)
{
intSpeed = currentSpeed + dT*gravVect/(distance*distance);
intPosit = currentPosit + dT*currentSpeed;
polozhenya[i] = intPosit-rigidBody.position;
currentSpeed = intSpeed;
currentPosit = intPosit;
gravVect = sun.GetComponent<Rigidbody>().position-currentPosit;
distance = gravVect.magnitude;
}
lineTraj.SetPositions(polozhenya);
}
The code is pretty much self contained, the for loop just calculates the next N positions. So polozhenya is the array of points, and it calculates a hundred or so and then puts them as points of the line object lineTraj
My main question is if I´m using the right timestep. According to the documentation the fixedDeltaTime is the time the physics engine uses for updates, so I thought it was right. I´m getting something like this:
The blue line is the proper trajectory the smaller object is following and the red one is the integrated one, which is closer to the real one in smaller orbits
So what do you guys think is going on? I thought by artificially making the timestep much smaller and got something like in the following picture, so I don't think that's the problem
Your answer
Follow this Question
Related Questions
How to make GameObject fall with the same gravity while using AddForce() 1 Answer
Charcter physics and groundedness 0 Answers
Confused about how AddForce works 1 Answer
left/right movement is slow when below ground level 0 Answers
How to make a player instantly reach to a change in gravity? 2 Answers