- Home /
2d collision detecting simultaneous collisions.
I've created a simple 2d tennis game. The game detects collision from the ball. If the ball hits the paddle it plays a sound and determines the direction that the ball will be sent to the other side. When a ball hits both the upper boundary and the paddle at the same time no collision is detected. Any insight on how I can get the collider to work?
I included some code and video. In the video the first hit does not fire off the "if ((col.gameObject.tag == "paddle"" when it hits the paddle and the wall at the same time. http://youtu.be/uxta9CxOBJs
void OnCollisionEnter2D(Collision2D col ) {
foreach(ContactPoint2D contact in col.contacts){
Debug.Log("col");
// Hit the left Racket?
if ((col.gameObject.tag == "paddle" && noman == false) {
audio.Play();
if (noscore == false){
player1Score++;
noscore = true;
}
Answer by SilentSin · Jul 26, 2014 at 05:12 AM
The problem is that you are using "col.gameObject.tag" instead of "contact".
The ball hits the paddle and wall, so it gets a collision message with 2 contacts. You loop through both contacts, but check col.gameObject.tag for both of them rather than checking the tag of the contact point.
What you want is if (contact.gameObject.tag
Also, you have 2 opening brackets after the if, but only one closing bracket.
Hey thanks a lot. This was a big step in the right direction. what was strange was it only returned 1 contact even though it collided with both objects. This seems like a glitch. I was able to solve it by using contact.point to work if it hits the wall. $$anonymous$$ind of crude but it worked. I'm going to build an example project and bring this issue up in the forums soon.
I'm not sure about 2D, but in 3D you would get a separate OnCollisionEnter call for every object you hit, where each one of them would have the contact point or points for that object. So if you overlap two parts of a terrain as well as a building, you would get 2 calls; one with the terrain's 2 contact points and the other with just 1 contact point for the building.
If my answer solved your problem, you should mark it as correct.