If you are wanting to retrieve the point of contact for a collision between the Ball and the Paddle you can use the following code;
/// <summary>
/// Handles the OnCollisionEnter2D event triggered by an incoming collider making contact with the Ball's collider
/// </summary>
/// <param name="collision">The Collision2D data associated with this collision</param>
private void OnCollisionEnter2D(Collision2D collision)
{
foreach (ContactPoint2D impact in collision.contacts)
{
if (collision.gameObject.name == "Paddle")
{
Vector3 paddleLocalImpactPoint = _paddle.transform.InverseTransformPoint(impact.point);
Debug.Log("Paddle Impact\n\n" +
"World: X = " + impact.point.x.ToString() + " Y = " + impact.point.y.ToString() + "\n" +
"Local: X = " + paddleLocalImpactPoint.x + " Y = " + paddleLocalImpactPoint.y + "\n" +
"\n-----------------------\n");
}
}
In the above example, we specifically only look for a collision with the Paddle, however, you could potentially check for any other GameObject also (a block for example).
impact is a ContactPoint2D and provides details about a specific point of contact involved in a 2D physics collision
point is a Vector2D and is the point of contact between 2 colliders in world space
Whilst retrieving the point of collision in the world space may be useful, it can also be useful to retrieve the point of collision local to the incoming collider (the Paddle in this scenario).
With a centralised pivot on your Paddle GameObject, a negative x value would indicate the impact occurred on the left hand side, a positive x value would indicate the impact occurred on the right hand side.
Note: The console only displays 2 line of information so the above is formatted in such a way that you click on the item and see the full information displayed in the expand section of the Console window, see below;
If you consider Block Breaker for example, if you can obtain the point of impact you could change the outbound vector of the ball based on the collision point.
hey many thanks, i didn’t know how to find out what collides with what, now I know thanks to you! it opens bunch of new possibilities for what i wanted to do in block breaker.
You’re more than welcome. It seemed like a useful thing to share.
In that cide example you can probably drop the for...each, I’m fairly confident either only one item will be returned, or, you’ll only be interested in the first item anyway, so you.might need to make a tweak etc.
As a mentioned in another post mucho thanks for providing the collision code .
As for the foreach I was pretty confident that it could be dropped - and the collision part of the code does function without it … but, you wouldn’t you need it to return the actual x,y co-ords or point of the of the hit? Haven’t got around to putting in the rest of the code yet!