Question by
ppozniak · Jun 06, 2019 at 09:21 AM ·
rigidbody2djumpgetbutton
Rigidbody2d jumps twice with Input.GetButton (is grounded check)
Hello. I am using 2d rigidbody for my character and the problem is when I'm using Input.GetButton("Jump")
instead of GetButtonDown
my player jumps twice.
To check for ground I am using isGrounded = capsuleCollider.IsTouchingLayers(groundLayer);
Here's the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField]
public LayerMask groundLayer;
public float playerSpeed = 10f;
public float jumpPower = 10f;
private float xInput = 0f;
private Rigidbody2D rb;
private bool jumpPressed;
private bool isGrounded = true;
private CapsuleCollider2D capsuleCollider;
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
capsuleCollider = gameObject.GetComponent<CapsuleCollider2D>();
}
// Update is called once per frame
void Update()
{
xInput = Input.GetAxisRaw("Horizontal");
jumpPressed = Input.GetButton("Jump");
}
void FixedUpdate()
{
Vector2 newVelocity = new Vector2(xInput * playerSpeed, rb.velocity.y);
rb.velocity = newVelocity;
isGrounded = capsuleCollider.IsTouchingLayers(groundLayer);
if (jumpPressed && isGrounded)
{
isGrounded = false;
rb.AddForce(new Vector2(0f, jumpPower), ForceMode2D.Impulse);
}
}
}
I could probably fix that by doing some timer related stuff, to prevent additional jumps too quickly, but I want to know if there's another way. The reason I'm using GetButton over GetButtonDown is that I want my character to jump constantly if player is holding Jump button. All the tutorials are using GetButtonDown
and I couldn't find any related topics :(
Best regards.
Comment
Your answer
Follow this Question
Related Questions
Rigidbody is not Jumping while Moving 0 Answers
Rigidbody is not Jumping while Moving 0 Answers