I have a character that a Boolean flag which determines whether or not he is jumping (if he is jumping, he cannot jump again). When he jumps, the jump flag is set to true, and when he collides with something it is set back to false (so he can jump again).
However, he only jumps once, and jump stays true even when it's supposed to reset to false. Why is this so? My definition for OnCollisionEnter()
is supposed to reset the flag.
var trump;
var jump = false;
function Start() {
// Assigns the Rigidbody to a variable
trump = GetComponent(Rigidbody2D);
// Variable Switches:
}
function OnCollisionEnter() {
jump = false;
trump.velocity.y = 0;
trump.velocity.x = 0;
}
function FixedUpdate() {
trump.velocity.x = Input.GetAxis("Horizontal") * 10;
if ((Input.GetKeyDown(KeyCode.UpArrow)) && (jump == false)) {
trump.AddForce(Vector2(0, 10), ForceMode2D.Impulse);
jump = true;
}
}
EDIT: Based on an answer given I tried adding the Collision
parameter to OnCollisionEnter()
, but it still doesn't look like the function is being called after I added a Debug.Log()
inside of it to check. Is there something else wrong?
function OnCollisionEnter(collision: Collision) {
jump = false;
Debug.log("He Hit The Wall");
trump.velocity.y = 0;
trump.velocity.x = 0;
}
Your function signature for OnCollisionEnter()
is incorrect. When defining these MonoBehaviour-specific functions, it is imperative that the name and parameters of the function match that shown in the documentation. Otherwise, the MonoBehaviour won't recognize them and the function won't be called when expected.
In this case, OnCollisionEnter()
requires a Collision
parameter:
function OnCollisionEnter(collision: Collision) {
jump = false;
trump.velocity.y = 0;
trump.velocity.x = 0;
}
Note: The above was written before the question was edited to implement the suggestion - before, OnCollisionEnter()
was being defined without a parameter.
However, in your case that isn't the only problem - you're using Unity's 2D physics, which means you should actually be using the 2D variant of the function: OnCollisionEnter2D
, which also takes a slightly different parameter of a Collision2D
.
So you would need:
function OnCollisionEnter2D(collision: Collision2D) {
jump = false;
trump.velocity.y = 0;
trump.velocity.x = 0;
}
Hope this helps! Let me know if you have any questions.