I am starting to make a 2D platformer. I figured out how to make the character jump, but when I tried to add in Collision Detection to make it to where the player can only jump on the ground, it wouldn't work. Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
Vector2 newPosition = new Vector2(0, 7);
float movementSpeed = 5f;
float jumpForce = 10f;
public bool isGrounded;
// Start is called before the first frame update
void Start()
{
GetComponent<Rigidbody2D>().MovePosition(newPosition);
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.A))
{
Vector2 position = this.transform.position;
position.x -= movementSpeed * Time.deltaTime;
this.transform.position = position;
}
if (Input.GetKey(KeyCode.D))
{
Vector2 position = this.transform.position;
position.x = movementSpeed * Time.deltaTime;
this.transform.position = position;
}
if (Input.GetKey(KeyCode.Space) && isGrounded == true)
{
Vector2 position = this.transform.position;
position.y = jumpForce * Time.deltaTime;
this.transform.position = position;
isGrounded = false;
}
}
void OnCollisionEnter2D(Collision2D other)
{
isGrounded = true;
}
}
CodePudding user response:
Sometimes this is problem of the collider that touches the ground. Try to make it higher, lower and try again. I had the same problem once and the solution was just adjusting the collider. Some times the collider is too low, so when you jump it touches the ground again so it becomes true and immediately stops jumping.
CodePudding user response:
No that wont do it. Try adding a Debug.Log(isGrounded) inside OnCollisionEnter2D() so you can see when it happens exactly maybe that will help you. By the way you haven't put any conditions inside the OnCollisionEnter2D() which means anything that enters it's collider will make isGrounded = true; .
