- Home /
Question by
Luckylou · Jun 12, 2017 at 08:43 AM ·
c#gameplatformerplayer movement
Jumping is randomly not working.
Hello,
I am new to Unity and just tried to make a little platformer. Most of the time it works fine, but sometimes the jump just won't work for a couple of seconds. I have no idea why that happens and I hope someone can maybe help me.
Thanks a lot!
This is my code for jumping:
[Range(1, 10)]
public float jumpVelocity;
public float fallMultiplier = 2.5f;
public float lowJumpMultiplier = 2f;
public LayerMask groundLayer;
Rigidbody2D rb;
bool IsGrounded()
{
Vector2 position = transform.position;
Vector2 direction = Vector2.down;
float distance = 0.7f;
RaycastHit2D hit = Physics2D.Raycast(position, direction, distance, groundLayer);
if (hit.collider != null)
{
return true;
}
else
{
return false;
}
}
void Awake () {
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate () {
if (Input.GetButtonDown("Jump"))
{
Jumpnow();
}
//Add better jumping
if (rb.velocity.y < 0)
{
rb.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
}
else if(rb.velocity.y > 0 && !Input.GetButton("Jump")){
rb.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
}
}
void Jumpnow()
{
if (!IsGrounded())
{
return;
}
else
{
rb.velocity = Vector2.up * jumpVelocity;
}
}
Comment