Framerate not performance-independent
I was following the Ruby's Adventure tutorial and at the end, when I built the game and ran it, I realized the framerate hadn't been performance-independent all along. Basically, the sprite needs to move to the chosen direction at a specific speed, so I multiply the direction vector by that speed and then by deltaTime. The speed is 3 and, through logs, I've checked that it all comes out to 3 units per second in the build, as well as in the editor. However, in the build, where the framerate is much higher, the character moves far slower. Here is the code for the Update() method:
void Update() {
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector2 move = new Vector2(horizontal, vertical);
if (!Mathf.Approximately(move.x, 0.0f) || !Mathf.Approximately(move.y, 0.0f)) {
lookDirection.Set(move.x, move.y);
lookDirection.Normalize();
}
animator.SetFloat("Look X", lookDirection.x);
animator.SetFloat("Look Y", lookDirection.y);
animator.SetFloat("Speed", move.magnitude);
Vector2 position = rb.position;
position += move * speed * Time.deltaTime;
rb.position = position; //MovePosition(position);
if (invincibilityTime != 0.0f) {
invincibilityTime -= Time.deltaTime;
if (invincibilityTime < 0.0f)
invincibilityTime = 0.0f;
}
if (Input.GetKeyDown(KeyCode.Space))
Launch();
if (Input.GetKeyDown(KeyCode.Return)) {
RaycastHit2D hit = Physics2D.Raycast(rb.position + Vector2.up * 0.2f, lookDirection, 1.5f, LayerMask.GetMask("NPC"));
if (hit.collider != null) {
NonPlayerCharacter NPC = hit.collider.GetComponent<NonPlayerCharacter>();
if (NPC != null)
NPC.DisplayDialog();
}
}
}
I've noticed that using transform.position = position; instead of the MovePosition method fixes this. However, this same fix does not work for the robots (the enemy in the tutorial). Here is the Update method for the robots:
void Update() {
if (!broken)
return;
timer -= Time.deltaTime;
Vector2 position = transform.position;
if (timer < 0.0f) {
timer = 3.0f;
direction = direction == 1 ? -1 : 1;
}
animator.SetFloat("Move X", direction);
position.x += Time.deltaTime * speed * direction;
rb.MovePosition(position);
}
I find it especially weird that transform.position = position; works for the main character and not the robots, since I move them roughly in the same way. As for the speed, it is 3.0f in both cases. I assume that this has something to do with the amount of time the physics system updates rigid bodies, as opposed to the amount of times Update is called.