Why does Collider2D.IsTouching have no effect? C#
The script checks if a Space key is pressed. If at this moment the player is touching a ground - do jump. But it does not!
void Update () {
if (Input.GetKey (KeyCode.Space)) {
isSpace = "Space Yes";
if (GetComponent<PolygonCollider2D> ().IsTouching (GameObject.FindWithTag ("ground0").GetComponent<BoxCollider2D> ())) {
isTouch = "Touch Yes";
GetComponent<Rigidbody2D> ().AddForce (Vector2.up * jumpForce, ForceMode2D.Impulse);
} else {
isTouch = "Touch No";
}
}
The main object is a triangle sprite tagged as "Player". It has Rigidbody2D, PolygonCollider2D, it's not Static. The second is a box (square sprite) tagged as "ground0" which has BoxCollider2D and not Static. I am also checking it with OnGUI onscreen message: Space works well, touching does not. I tried to check IsTouching separately (as below): GUI says NO it doesn't touch.
if (GetComponent<PolygonCollider2D> ().IsTouching (GameObject.FindWithTag ("ground0").GetComponent<BoxCollider2D>())) {
isTouch = "Touch Yes";
} else {
isTouch = "Touch No";
}
I also tried to change Colliders to different types (Polygon, Edge etc.) — no effect. And I tried adding ==true to the if-statement (I think it doesn't matter). Btw, is it fine to use FindWithTag here like I do?
Answer by charmpie · Mar 16, 2016 at 03:24 AM
Update 1: It's my inexperience. The point is that FindWithTag finds only one object with this tag. So if we want our object to interact with every object with this tag (i.e. to jump from every platform with tag "ground"), we should use ForEach loop with FindGameObjectsWithTag.
Update 0: Some kind of solution has been found. I created an empty project with just two objects and typed the same code and it worked well. Then I went back to my problematic project. I realised that somehow I myself created the problem. Since my scene has many platforms with this exact "ground0" tag (because I duplicated them), I thought maybe a tag should be unique for every object. I tried changing the tag "ground0" to "ground" and it worked. Just to be sure that it is the case, I changed a couple of object tags with a new "ground" tag. But it still worked! Then I thought maybe the number was the problem and changed tags to "test0", and yet it worked! I can't imagine what could I do wrong, or was it really me? If you have any thoughts or encountered the same problem please reply.
Thanks for the post I didn't realize that .isTouching would be looking for a specific collider ins$$anonymous$$d of returning true when touching any collider.
Your answer
Follow this Question
Related Questions
Physics 2D with tile collider corner problem 2 Answers
Had to turn off gravity scale, but now player goes through walls 0 Answers
Problem with hitboxes and hurtboxes 0 Answers
Top-down collisiondetection 0 Answers
2D Physics not working correctly 1 Answer