- Home /
Can someone help me with the jumping in this Player Controller script?
This script lets me jump once in my 2D platformer, but after that I can't jump again. Why isn't the collision making canJump equal true? Here is my entire Player Controller script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Sprites;
public class PlayerController : MonoBehaviour
{
public float speed;
public float jumpSpeed;
public Rigidbody2D rb;
private Vector3 movement;
private bool canJump=true;
void Start ()
{
rb = GetComponent<Rigidbody2D>();
bool canJump = true;
}
void Update ()
{
transform.rotation = new Quaternion (0.0f, 0.0f, 0.0f, 0.0f);
if (Input.GetKey (KeyCode.A))
{
transform.Translate (-Vector3.right * Time.deltaTime * speed);
}
if (Input.GetKey (KeyCode.D))
{
transform.Translate (Vector3.right * Time.deltaTime * speed);
}
if (Input.GetKeyDown (KeyCode.Space)&&canJump)
{
rb.AddForce (transform.up * jumpSpeed);
canJump=false;
}
}
void OnCollision(Collision col)
{
if (col.gameObject.tag == "Ground")
{
canJump=true;
}
}
}
Answer by Igor_Vasiak · Jun 23, 2017 at 02:28 PM
It’s because there is no such void called OnCollision. For 2D games you need OnCollisionEnter2D (Collision2D collision). Hope I’ve helped.
EDIT:
And please, PLEASE don’t forget that OnCollisionEnter2D ONLY WORKS WITH 2D COLLIDERS! It means that if you have your player using a BoxCollider2D and your ground with a BoxCollider, then the player will FALL THROUGH THE GROUND, since BoxCollider2D only collides with other 2D collider components.
And you can’t use BoxCollider2D with a Rigidbody component as well, you will need a Rigidbody2D component.
Your answer
Follow this Question
Related Questions
Goal Collision for pong game 0 Answers
Jumping in only the direction of the last key pressed 0 Answers
2d-platformer climb 2 Answers
Box goes through walls 2 Answers
Changing a Sprite when Collision occurs 2 Answers