- Home /
C#: Climb ledge while inside collider
Ok so Im trying to do the following: 1-You reach a ledge. 2-Press the jump button. 3-The character climbs up.
I got this sorta working. Basically I have a collider on the ground and when you step on it plays the "climb up" animation.
Here's the code Im using to trigger this:
// Create a reference to the animator component
private Animator animator;
void Start ()
{
// initialise the reference to the animator component
animator = GetComponent<Animator>();
}
// check for colliders with a Trigger collider
// if we are entering something called JumpTrigger, set a bool parameter called JumpDown to true..
void OnTriggerEnter(Collider col)
{
if(col.gameObject.name == "ClimbHIGHTrigger")
{
animator.SetBool("ClimbHIGH", true);
}
}
// ..and when leaving the trigger, reset it to false
void OnTriggerExit(Collider col)
{
if(col.gameObject.name == "ClimbHIGHTrigger")
{
animator.SetBool("ClimbHIGH", false);
}
}
This currently works, but it has two problems:
1-It plays the climb up animation automatically when you enter the collider, and I only want it to play when you pres the jump key.
2-It will play the animation in whatever direction you are looking at rather than the wall.
To try and solve issue #1 I tried the following:
if(col.gameObject.name == "ClimbHIGHTrigger" && Input.GetButtonDown ("Jump"))
Sadly, while the code itself compiles without errors nothing happens when I enter the collider and press jump.
I reckon that issue #2 is probably more complex to tackle, but some pointers in fixing #1 would be a great help.
What method is that if check in? It should be in OnTriggerStay()
Answer by HarshadK · Oct 17, 2014 at 07:22 AM
In line with what @Habitablaba said, you need to use OnTriggerStay while you are checking for if the player pressed jump key while in the trigger because the OnTriggerEnter will be executed only once when the player enters the trigger so if player does not press the jump key while that is executed then it will not climb, ever. So you should use OnTriggerStay().
Something like:
void OnTriggerStay(collider col)
{
if(col.gameObject.name == "ClimbHIGHTrigger" && Input.GetButtonDown ("Jump"))
{
// Perform climb here
}
}