Inconsistent jump height and double jumping issues with rigidbody2D on a sprite
Basically i cant figure out how to get my jumping to work without having issues. If i use update like .. private int jumpCount public int maxJumps and have it count down along with using a isGrounded bool then i can prevent double jumps in update function fairly consistently. However every fourth or so jump the jump will randomly go up about twice as high if im using update regardless of jumpStrength not changing. So i tried using fixed update.. it did not go well. Basically in fixed update everything is even worse. Regardless of whether i use a isGrounded bool with a ground tag or the counter or both it seems pretty random as far as the jump cooldown is concerned and still attempts to double jump somewhat randomly if your spamming the space key. Any suggestions? Heres a look at what i have if you like .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField]
private int JumpCount = 0;
[SerializeField]
private int MaxJumps = 1; //max amount you can jump ie 2 for double jump
// private bool isGrounded;
[SerializeField]
private float jumpStrength = 20f;
[SerializeField]
private bool dead;
[SerializeField]
private float defaultAnglespeed = 0f;
[SerializeField]
private float anglespeed = 30.0f;
[SerializeField]
private float moveSpeed = 100f;
private Rigidbody2D rb2D;
// Use this for initialization
void Start ()
{
rb2D = GetComponent<Rigidbody2D>();
JumpCount = MaxJumps;
}
private void FixedUpdate()
{
walk();
if (dead != true)
{
rb2D.MoveRotation(defaultAnglespeed * Time.fixedDeltaTime);
}
else if (dead == true)
{
}
}
// Update is called once per frame
void Update ()
{
}
private void walk()
{
if ( Input.GetKey("d"))
{
if ( dead != true)
rb2D.AddForce(transform.right * moveSpeed * Time.deltaTime);
rb2D.MoveRotation(-5f + anglespeed * Time.fixedDeltaTime);
}
else if (Input.GetKey("a"))
{
if (dead!=true)
rb2D.AddForce(-transform.right * moveSpeed * Time.deltaTime);
rb2D.MoveRotation(5f + anglespeed * Time.fixedDeltaTime);
}
else if (Input.GetKeyDown("space") == true) //&& isGrounded
{
if (JumpCount > 0 )
{
rb2D.AddForce(transform.up * jumpStrength );
JumpCount = JumpCount - 1;
}
else if (JumpCount <= 0)
{
}
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
switch (collision.gameObject.tag)
{
case "floor":
{
JumpCount = MaxJumps;
// isGrounded = true;
//print("I'm touching the ground");
return;
}
default:
{
//isGrounded = false;
}
return;
}
}
}