3
\$\begingroup\$

In my 2D billiards game, I have it so that when the user clicks and drags with their mouse, a Physics2D.CircleCast is projected from the cueball to wherever the mouse is. If the circle happens to hit the red ball, a line is rendered from the red ball's position to the direction of the normal of the collision. So it's supposed to predict where the red ball will go when it gets hit by the cueball.

If you look at the first gif below, you'll see that it works if the red ball gets hit at its center (or close to it). The red ball ends up moving more or less along the predicted line.

Successful prediction

However, if you look at this second gif, you'll see that if the red ball gets hit closer to its edge, the predicted line is much less accurate.

Incorrect prediction

I was just wondering why this was and how can I fix it?

Here's the prediction code I use:

 if (Input.GetMouseButton(0) && cueBall)
 {
        Vector2 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
        var direction = (mousePos - (Vector2)cueBall.position).normalized;
        var hit = Physics2D.CircleCast(cueBall.position, _radius, direction, Mathf.Infinity);

        if (hit)
        {
            _lineMain.Draw(cueBall.position, hit.point);
            _ghostBall.SetPosition(hit.point - (direction * _radius));                
            _lineTarget.Draw(hit.point, hit.point - hit.normal); //This is the predicted trajectory.               
        }
 }
\$\endgroup\$
4
\$\begingroup\$

The issue was that the radius that I inputted into the CircleCast was not accurate. Initially, I set the radius to that of the cueball's circlecollider2D, which would be .09f. But since I lowered the transform scale of the ball from 1 to .8f, that radius was no longer accurate. To get the accurate radius in code, you get either the the x or y value of its extents, which in this case would be .07200003f (.8f * .09f). So simply setting the radius to _cueBall.GetComponent<CircleCollider2D>().bounds.extents.x solved the problem. Sorry for any confusion this may have caused anyone else.

enter image description here

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.