Help with Player Jumping Script In 2D Platformer (C#)
Hi, I'm making a 2D platformer using C# and need help with my jumping script. My character jumps fine, except when its comes to slopes, it doesn't work so well. Basically when I jump and land on a slope and continue to move, it says that my player is not grounded and I cant jump again, until I get off the slope and it says I'm grounded again after 1 second. Its a really weird problem that I have no idea how to fix. I'm not using "groundCheck" because I've tried using it so many times before but I just cant get it to work. But if you can show me how to use "groundCheck" that would be great. But I just need my player to jump normally when it comes to slopes.
Script v v v
using UnityEngine;
using System.Collections;
public class PlayerJump : MonoBehaviour{
private PlayerControlsScript player;
public bool grounded = true;
public float jumpPower = 300;
private bool hasJumped = false;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (!grounded && GetComponent<Rigidbody2D>().velocity.y == 0 && hasJumped == false)
{
grounded = true;
}
if (Input.GetKey(KeyCode.Space) && grounded == true)
{
hasJumped = true;
}
}
void FixedUpdate()
{
if (hasJumped)
{
GetComponent<Rigidbody2D>().AddForce(transform.up * jumpPower);
grounded = false;
hasJumped = false;
}
}
}
Answer by UsmanAbbasi · May 16, 2016 at 05:53 AM
This is not the right way to check if player is grounded or not.
if (!grounded && GetComponent<Rigidbody2D>().velocity.y == 0 && hasJumped == false)
{
grounded = true;
}
When you are on slope and moving then velocity.y may not be equal to 0 which is making this condition false. You should use Physics.Raycast2d to check the distance of player from the ground i.e. if player is jumping or not.