Question by
Leon08x · Mar 02, 2020 at 10:50 PM ·
c#2d-platformerjumpingisgrounded
2D-Platformer wrong jumps
I followed Lost Relic Games' "Game Dev Basics: Let's Make a 2D player controller in C# and Unity!" at least the part on how to make a character jump, yet my character jumps even when not grounded. I've even seen that the character can jump when the "isGrounded" box in the Inspector tab is unchecked. Ty all in advance. Here's the code(only thing I changed to ask this question were mentions of the character's name with just "Character"):
public class PlayerController2D_Character : MonoBehaviour
{
private Rigidbody2D rb2d;
private SpriteRenderer sprite;
private Animator anim;
[SerializeField]
private float runspeed = 4;
[SerializeField]
private float jumpforce = 8;
[SerializeField]
bool isGrounded;
[SerializeField]
Transform groundCheckM;
[SerializeField]
Transform groundCheckR;
[SerializeField]
Transform groundCheckL;
void Start()
{
anim = GetComponent<Animator>();
rb2d = GetComponent<Rigidbody2D>();
sprite = GetComponent<SpriteRenderer>();
}
private void FixedUpdate()
{
if ((Physics2D.Linecast(transform.position, groundCheckM.position, 1 << LayerMask.NameToLayer("Ground"))) ||
((Physics2D.Linecast(transform.position, groundCheckR.position, 1 << LayerMask.NameToLayer("Ground"))) ||
((Physics2D.Linecast(transform.position, groundCheckL.position, 1 << LayerMask.NameToLayer("Ground"))))))
{
isGrounded = true;
}
else
{
isGrounded = false;
anim.Play("CharacterJump");
}
if (Input.GetKey("d") || Input.GetKey("right"))
{
rb2d.velocity = new Vector2(runspeed, rb2d.velocity.y);
if (isGrounded)
anim.Play("CharacterRun");
sprite.flipX = false;
}
else if (Input.GetKey("a") || Input.GetKey("left"))
{
rb2d.velocity = new Vector2(-runspeed, rb2d.velocity.y);
if (isGrounded)
anim.Play("CharacterRun");
sprite.flipX = true;
}
else
{
if (isGrounded)
anim.Play("CharacterIdle");
rb2d.velocity = new Vector2(0, rb2d.velocity.y);
}
if (Input.GetKey("space") && isGrounded)
{
rb2d.velocity = new Vector2(rb2d.velocity.x, jumpforce);
anim.Play("CharacterJump");
}
}
Comment