- Home /
I can't jump sometimes
I can't jump sometimes when i land in another platform after jump. I not 100% sure how to use the funtion void OnTriggerEnter2D():
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerMove : MonoBehaviour {
public float MoveSpeed;
public float JumpVelocity;
private bool OnTheFloor;
private Rigidbody2D RBody;
// Use this for initialization
void Start () {
OnTheFloor = false;
RBody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update() {
Movement();
}
void Movement() {
if (Input.GetKey(KeyCode.RightArrow))
{
RBody.velocity = new Vector2(MoveSpeed, RBody.velocity.y);
transform.eulerAngles = new Vector2(0, 0);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
RBody.velocity = new Vector2(-MoveSpeed, RBody.velocity.y);
transform.eulerAngles = new Vector2(0, 180);
}
if (Input.GetKey(KeyCode.LeftArrow)==false && Input.GetKey(KeyCode.RightArrow) == false) {
RBody.velocity = new Vector2(0f, RBody.velocity.y);
}
if (Input.GetKey(KeyCode.Space) || Input.GetKey(KeyCode.UpArrow)) {
if (OnTheFloor)
{
RBody.velocity = new Vector2(RBody.velocity.x, JumpVelocity);
}
}
//evito que tenga velocidad cuando gira
RBody.angularVelocity = 0f;
}
void OnTriggerEnter2D()
{
OnTheFloor = true;
}
void OnTriggerExit2D()
{
OnTheFloor = false;
}
}
Answer by Commoble · Mar 19, 2017 at 06:28 PM
OnTriggerEnter2D is a message function; Unity's message system allows functions with known names to be called on components without an actual reference to that component. One downside is that due to details on how it works (which I won't go into here), your IDE (MonoDevelop, Visual Studio, etc), won't tell you if your function's name or arguments are incorrect, which is one of many reasons why you should always read the documentation on any built-in function or message before you use it.
As shown in the documentation for OnTriggerEnter2D in that link, this is how you should use them:
void OnTriggerEnter2D(Collider2D other)
{
OnTheFloor = true;
}
void OnTriggerExit2D(Collider2D other)
{
OnTheFloor = false;
}
The Collider2D argument can have any name (it doesn't have to be "other"), but the function has to have the Collider2D argument or Unity won't recognize it as a trigger message.