Hey Unity, I decided to start working on an old project of mine again and I've ran into an issue I've ran into before and I did manage to fix it after some help on here so I was wondering if you guys could help me fix this again So the issue that I'm having right now is that if I stand still and jump I just the way I want my character to jump BUT if I run and jump at the same time my character for some reason jumps higher than it should, this is my code if has a solution please let me know!: https://gyazo.com/164b143f3ccc58808aaba58e1b1f6ed9 Code (csharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { public AudioClip jump; private AudioSource audioSource; public float Speed = 5; private Rigidbody2D rb; public bool isGrounded; public LayerMask whatIsGround; private Collider2D col; public bool JumpSoundPlaying = false; public float JumpVelocity = 10; // Use this for initialization void Start() { rb = gameObject.GetComponent<Rigidbody2D>(); audioSource = GetComponent<AudioSource>(); col = GetComponent<Collider2D>(); } void FixedUpdate() { isGrounded = Physics2D.IsTouchingLayers(col, whatIsGround); if (Input.GetKeyDown("space")) { if (isGrounded) { rb.AddForce(new Vector2(0, JumpVelocity), ForceMode2D.Impulse); if (!JumpSoundPlaying) { StartCoroutine("JumpSound"); } } } float moveHorizontal = Input.GetAxisRaw("Horizontal"); Vector2 movement = new Vector2(moveHorizontal, 0); transform.Translate(movement * Speed); /* -=== Auto run ===- transform.Translate(Speed * Time.deltaTime, 0f, 0f); -=== Auto run ===- */ } IEnumerator JumpSound() { audioSource.clip = jump; audioSource.Play(); JumpSoundPlaying = true; yield return new WaitForSeconds(0.1f); JumpSoundPlaying = false; } }
You might want to consider splitting up your FixedUpdate. That method can be called more (or less) than once per frame. If it gets called more than once, then line 56 will move the object more than expected. You only really want line 39 in FixedUpdate- move the rest into Update. See if that fixes the problem.
To add to Doug's comment, it can happen less than once per frame if the frame rate is higher than 50 (or more, if you changed the rate in project settings). This means if a frame that received the new key down when polling input does not have fixed update run, the input will be loss. The player could press the space bar, even hold it down, and nothing happen.
And not only that, the only input getting you wanna do in fixed update is GetKey, the normal one not GetKeyDown or GetKeyUp, they refresh by the visual frame's update and you will miss your inputs if they don't run side by side (or frame-by-frame). Take the input in Update() and flag a logic gate in FixedUpdate to jump when the next physics tick happens.