C# Crouch Issue
I have been working on a game recently and when I crouch to go under an object I can stand up then that sends me half through the floor. I made a script that was 'supposed' to fix that but it didnt... Please help! Code- void Update() { //Crouch if (Input.GetKey(KeyCode.S) || (Input.GetKey(KeyCode.DownArrow))) { speed = 5f; gameObject.GetComponent().SetBool("IsCrouching", true); GetComponent().radius = 0.3f; GetComponent().enabled = false; }
if (Input.GetKeyUp(KeyCode.S) || (Input.GetKeyUp(KeyCode.DownArrow))) {
if (crouch == false)
{
speed = 20f;
gameObject.GetComponent<Animator>().SetBool("IsCrouching", false);
GetComponent<CircleCollider2D>().radius = 0.6f;
GetComponent<BoxCollider2D>().enabled = true;
}
}
}
void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.tag == ("crouch"))
{
crouch = false;
}
}
void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.tag == ("crouch"))
{
print("Detected");
crouch = true;
}
}
}
I have this set up to detect the collision-
I am not sure what the issue is!
Answer by $$anonymous$$ · Jun 27, 2016 at 07:17 AM
The collision methods will never be called by your Crouch Check gameObject because it has its BoxCollider2D set to trigger but in your script you are calling OnCollisionEnter2D/OnCollisionExit2D. if the component circled in your screenshot is meant to activate those methods they need to be OnTriggerEnter2D/OnTriggerExit2D.
https://docs.unity3d.com/ScriptReference/Collider2D.OnTriggerEnter2D.html
Also, Input.GetAxis("Vertical") will get the input from both the S key and Down arrow. Input.GetAxis("Vertical") will equal 1 when the Up or W key is pressed, -1 when the Down or S key is pressed and 0 otherwise.
so if (Input.GetKeyUp(KeyCode.S) || (Input.GetKeyUp(KeyCode.DownArrow)))
is the same as if(Input.GetAxis("Horizontal" < 0)
Your answer
Follow this Question
Related Questions
Can't get Collision to detect triggers in unity 2d 4 Answers
Applying a script to two objects not working 2 Answers
Is calling OnCollisionEnter2D on allot of GameObjects leading to worse performance? 0 Answers
Inventory Script 0 Answers
Delete prefab clone when collided with the player, Unity 2D 1 Answer