Hi everyone!
I’m working on a 2D billiard game in Unity, but I’ve run into an issue with Physics2D.CircleCast. Sometimes, it gives me inaccurate or unexpected results for collision detection and sometimes wrong direction which its only happens when aiming at the very ending edge of the circle target.
See the video
hit = Physics2D.CircleCast(ball.position, ballRadius, stick.up, 99, layerMaskBallsAndWalls);
if (hit.collider.CompareTag("Ball"))
{
targetBall = hit.collider.transform;
targetDirectionLine.positionCount = 2;
targetDirectionLine.SetPosition(0, targetBall.position);
Vector3 targetDir = (hit.transform.position - new Vector3(hit.centroid.x, hit.centroid.y, 0)).normalized;
targetDirectionLine.SetPosition(1, (Vector3)hit.centroid + targetDir * mappedLength);
}
Thank you!
Sounds like a bug… time to find out what you’re hitting with that CircleCast and why it is wrong.
From the hit you can find the name of what you hit.
From the docs you can find more about how to do that.
Time to start debugging!
By debugging you can find out exactly what your program is doing so you can fix it.
Sometimes with spatial problems like this it can be useful to use things like Debug.DrawLine() to visualize what’s happening in realtime.
Use the above techniques to get the information you need in order to reason about what the problem is.
You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.
Once you understand what the problem is, you may begin to reason about a solution to the problem.
Hey thanks for the reply! after debugging it.
at certain angles, the circle cast would sometimes detect a collision and sometimes miss it by a very small margin. what I noticed:
- When the angle is -0.600407, the circle cast detects the target.
- At -0.600408, it doesn’t.
- Similarly, during the shot:
- -0.6172344 results in the cue ball hitting the target.
- -0.6172345 results in it missing.
While both balls have a radius of 0.25, so I slightly increased the radius used in the circle cast. if a shot would result in a collision, the circle cast will also register it.
I’m not sure if this is a default behavior in Unity where circlecast has some margin, but this adjustment provided more reliable results.
For handling the direction:
- I saved the target from the targetDir direction upon shot.
- On Collision Enters for the targetBall, the target ball maintains its speed but its changes to targetDir direction by sending it from the cue ball’s script.
- A condition checks if the ball is the target to update its direction as needed since I have more billiard target balls.
2 Likes