At first, basic movement is really simple. You have a direction and a speed, you multiply them together which gives you the total movement for that frame. Simple. Jumping is similiar but on one axis and you have to decrease the speed over time (gravity) like so:
Jump button pressed - Set jump speed to X (lets say 10 meters per second)
Move up by jump speed (multiplied by the amount of time between frames because we're in meters per second)
Take gravity amount away from jump speed
Repeat 2 and 3 until you move up then back down then hit the floor then give control back to normal movement
But there is a problem with this way that isn't clear at first. This calculation is semi frame rate dependant. We don't want that, we want to mimic the result as accurately as possible not relying on the framerate. For example:
Let's say our frame rate is at a constant 0.5 seconds per frame (some serious lag)
Our initial jump force is at 10 m/s
Gravity acceleration is 9.83 m/s (real life)
You press jump, Y speed is set to 10 m/s. It has been 0.5 seconds so we multiply 10 x 0.5 to get 5. That means we moved 5 meters this frame. We then subtract gravity from our current Y speed:
Gravity is 9.83 multiplied by 0.5 seconds gives us 4.915. So we subtract that from Y speed to get a new Y speed of 5.085.
So, assuming we started at a Y position of 0, we are now at position 5 and our speed is 5.085.
Ok, now let's say our framerate is at 0.25 seconds a frame, we do the same maths with the same initial speed and gravity:
Frame 1: Movement amount = 10 x 0.25 = 2.5
Frame 1: New Movement Speed = 10 - (9.83 x 0.25) = 7.5425
Frame 2: Movement amount = 7.5425 x 0.25 = 1.885625
Frame 2: New Movement Speed = 7.5425 - (9.83 x 0.25) = 5.085
After frame 2, our total movement would be 2.5 + 1.885625 = 4.385
Now, in both examples, the exact same amount of time has passed, so we would expect the same results. However, in example 2, the movement speed is the same; 5.085 but the total movement is different. In example 1 it was 5, in example 2; 4.385. So which one is correct? Neither. The second example is more accurate however. Infact the result becomes more accurate with faster framerates, but we don't want that, we want the same result regardless.
To overcome this, I took to trusty google and did that thing where you search for stuff. Ended up on a nice physics website that I should have bookmarked with lots of equations all named what they do. After locating the right one, I implemented it into my code:
Glorious. This will calculate the correct movement amount. Calculating the new speed is the same as before, as this gave consistent results.
Now with this running the jumping and gravity system, I can safely ensure that my movement will be stable as well as PHYSICALLY BASED MATE. PC MASTER RACE! 6000 FRAMES PER SECOND
xoxoxooxox
0 comments:
Post a Comment