- Home /
why is oncollisionenter not working half the time?
I am making DX ball.
for the movement of the ball, it would be too hard to use a rotation to make a reflection. so instead, I made 2 tags, border X and Y, and 2 vars for the speed of the ball on the x and y. I added these tags on the borders of the screen, and on 2 colliders for each brick. the problem is, when the ball hits the brick, the ball reacts to the collision, but dosent get an oncollisionenter() call for some reason and the brick dosent get destroyed and the ball dosent reflect.
here's my code for the ball movement:
public Rigidbody2D rb;
public float movespeed = 1f;
private float speedX;
private float speedY;
void FixedUpdate()
{
transform.position = new Vector3(transform.position.x + (speedX * (movespeed/10)), transform.position.y + (speedY * (movespeed/10)), 0);
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "borderX")
{
speedX *= -1f;
Debug.Log("border X");
}
if (other.gameObject.tag == "borderY")
{
speedY *= -1f;
Debug.Log("border Y");
}
}
Answer by Yuki_Rain · May 30 at 06:14 PM
do not set position while you are using rigidbody, use rigidybody.move to move your gameobject.
Answer by tushardholakiya · May 28 at 06:06 AM
Try to add debug outside if condition to check it's invoking OnCollosionEnter2D when it actually enters or not
void OnCollisionEnter2D(Collision2D other)
{
Debug.Log(other.gameobject.name);//------ Ad this line
if (other.gameObject.tag == "borderX")
{
speedX *= -1f;
Debug.Log("border X");
}
if (other.gameObject.tag == "borderY")
{
speedY *= -1f;
Debug.Log("border Y");
}
}
can you inspector video pic of ball object(where this script is attached)
thank you for the response!
I tried adding the debug.log statement outside the if statement, and it turns out it's not doing oncollisionenter2D() at all. for the picture of the ball, I added a picture of the ball's inspector below.
Your answer
![](https://koobas.hobune.stream/wayback/20220613061055im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Prevent a fast moving ball from passing through a wall 2 Answers
contuouse collision detection malfunction 2 Answers
How to get rid of jumpy collisions? 1 Answer
Object collisions failing with fast movement 1 Answer
OnParticleCollision doesn´t work 0 Answers