I am trying to implement the physics of a canon-ball (a little cumbersome code and that is fine and I don't really need to change it as I am learning).
I think I have done physics numerical method correctly but the problem is that my computer adds the numbers wrong, and it gives me terrible results.
![alt text][1]
[1]: /storage/temp/79374-c9c2525bc06551417d58a1e37971240f.png
Just take a look at this specific variable in one example of a loop in a "for" loop. I print out the loop number, do calculations and then print out the variables.
That means that for this calculation I need to use the previous vy. The top vy is 22.47091.
As you can see at the bottom which I have highlighted the C is: -0.0009003537
This is a code snippet:
float c = (a2y * dt * 0.5f);
float v3y = (vy + c);
V3y according to Unity becomes 22.69472 but that cannot be correct because 22.47091+(-0.0009003537) = 22.46190646
The loop:
for (int i = 0; i < 1000; i++) {
Debug.Log(i);
RungakuttaX(vx, sx, vy, sy, dt);
gameObject.transform.position = new Vector3(sx, sy, 0);
}
The rest of the code:
private void RungakuttaX(float vx, float sx, float vy, float sy, float dt) {
float v1x = vx;
float s1x = sx;
float v1y = vy;
float s1y = sy;
float a1x = FormelX(v1x, v1y);
float a1y = FormelY(v1x, v1y);
float v2x = (vx + (a1x * dt * 0.5f));
float s2x = (sx + (v1x * dt * 0.5f));
float v2y = (vy + (a1y * dt * 0.5f));
float s2y = (sy + (v1y * dt * 0.5f));
float a2x = FormelX(v2x, v2y);
float a2y = FormelY(v2x, v2y);
float v3x = (vx + (a2x * dt * 0.5f));
float s3x = (sx + (v2x * dt * 0.5f));
float c = (a2y * dt * 0.5f);
float v3y = (vy + c);
float s3y = (sy + (v2y * dt * 0.5f));
float a3x = FormelX(v3x, v3y);
float a3y = FormelY(v3x, v3y);
float v4x = (vx + (a3x * dt));
float s4x = (sx + (v3x * dt));
float v4y = (vy + (a3y * dt));
float s4y = (sy + (v3y * dt));
float a4x = FormelX(v4x, v4y);
float a4y = FormelY(v4x, v4y);
this.vx = vx + ((dt/6) * (v1x + 2*v2x + 2*v3x + v4x));
this.sx = sx + ((dt/6) * (s1x + 2*s2x + 2*s3x + s4x));
this.vy = vy + ((dt/6) * (v1y + 2*v2y + 2*v3y + v4y));
this.sy = sy + ((dt/6) * (s1y + 2*s2y + 2*s3y + s4y));
Debug.Log("vy:"+vy+" v1y:" + v1y + " a1y:" + a1y + " v2y:" + v2y + " a2y:" + a2y + " c:" + c +" v3y:" + v3y + " a3y:" + a3y + " v4y" + v4y + " a4y" + a4y + "---");
}
public float FormelX(float vx, float vy) {
float v = Mathf.Sqrt((vx * vx) + (vy * vy));
float d = (0.5f * p * (v * v) * c * a)/m;
float dx = -d * (vx / v);
if (v != 0)
{
return dx;
}
else
{
return 0;
}
}
public float FormelY(float vx, float vy) {
float v = Mathf.Sqrt((vx * vx) + (vy * vy));
float d = (0.5f * p * (v * v) * c * a)/m + g;
float dy = -d * (vy / v);
if (v != 0)
{
return dy;
}
else
{
return 0;
}
}
↧