Unity 2D physics: problem about gravity simulation
What I am trying to do is: when user press space button, I will give the game object an vertical velocity for jump, and minus an gravity number in each frame (in update function) to simulate gravity effect. Here is my code:
float gravity = -10;
float jumpVelocity = 200;
float logicSpeedY = 0;
float actualSpeedY = 0;
public int targetFPS = 30;
bool jumped = false;
void Awake()
{
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = targetFPS;
}
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
logicSpeedY = jumpVelocity;
jumped = true;
}
if (jumped)
{
logicSpeedY = logicSpeedY + gravity;
actualSpeedY = logicSpeedY * Time.deltaTime;
transform.Translate(new Vector3(0, actualSpeedY, 0));
}
}
These code worked in a way. But the problem is, the game object jump distance is different in different FPS.
I think I have avoid this because the speed multiplied by Time.deltaTime
. So why this still happened ? How can I let the jump distance is equal in different FPS ?
Because when the FPS is low, Time.deltaTime become large, then you hit jump at that frame, the player should jump higher. Jumping with Time.deltaTime should be avoid. I guess you are new to Unity, I recommend to use the built-in physics (rigidbody/charactercontroller) ins$$anonymous$$d of implementing your own.
But if I handle horizontal speed in this way: input.x * speed * Time.deltaTime
, it could move in constant speed in different FPS, why vertical can not ?
because the horizontal movement is a straight line while a jump is an arc. think of the way you calculate movement as if you were adding distances of different length on top of each other. while in a straight line, there's no offset in any other axis, but with a jump arc every slight difference leads to a different position from which any future change differs.
if you want to implement the jump yourself use a formula describing the jump arc where you can pass in the current time and it gives you the position of the arc.