How to Ground check a character?
I am following a tutorial and I don't know if it's because I have the newer version or I did something incorrectly. (I realized some of the scripts were not valid in the updated Unity.) I can constantly hit the space bar and my character will continue to jump. I tried making an 'Empty Child' but it didn't recognize that I placed with the player. I have no clue how to fix this issue.
using UnityEngine;
using System.Collections;
public class Rose_Contoller : MonoBehaviour {
public Transform groundCheck;
public float groundCheckRadius;
public LayerMask WhatIsGround;
private bool grounded;
public float moveSpeed;
public float jumpHeight;
// Use this for initialization
void Start () {
}
void FixedUpdate () {
grounded = Physics2D.OverlapCircle(groundCheck.position,groundCheckRadius,WhatIsGround);
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space)){
GetComponent <Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x,jumpHeight);
}
if (Input.GetKey(KeyCode.D)){
GetComponent <Rigidbody2D>().velocity = new Vector2(moveSpeed,GetComponent<Rigidbody2D>().velocity.y);
}
if (Input.GetKey(KeyCode.A)){
GetComponent <Rigidbody2D>().velocity = new Vector2(-moveSpeed,0);
}
}
}
grounded is being assigned but it's not being used anywhere, shouldn't you be checking if grounded is true before jumping?
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Space)) {
if (grounded) {
GetComponent <Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x,jumpHeight);
}
}
This is assu$$anonymous$$g that updating grounded is working.
Answer by CustomStudios · Feb 27 at 09:57 PM
If you are talking about what I think you are to ground check just do an OnCollisionEnter then an if statement like this:
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.tag == "Ground")
isgrounded = true;
}
Make sure you have a is grounded variable that you use.
Your answer
Follow this Question
Related Questions
Cant double jump with grounded code,Being grounded and Double Jumping 0 Answers
How can i add a groundCheck to my script? 1 Answer
Player no longer jumping 0 Answers
Ground the object to only jump once in 2D platformer game. 0 Answers
isGrounded not working,is grounded stops players from jumping 1 Answer