- Home /
Ball bounces in the wrong direction
I have written a script that is is applying a force to a ball and then makes the ball bounce off the objects it collides with. It works very well except in the situation in the attached photo where the ball is applied a force to make it go straight up, but it seems to only detect collision with one of the lines in the cross (detects one of them, then the other right after in the next frame or so, resulting in the first collision being "ignored"), resulting in the ball bouncing down to the far right instead of straight downwards. Any ideas how to fix this?
private void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.velocity = initialVelocity;
s=false;
force = new Vector2(0f,1f);
}
private void Update()
{
lastFrameVelocity = rb.velocity;
if (s)
rb.AddForce(force);
}
private void OnCollisionEnter2D(Collision2D collision)
{
Bounce(collision.contacts[0].normal);
s = false;
}
private void Bounce(Vector3 collisionNormal)
{
var speed = lastFrameVelocity.magnitude;
var direction = Vector2.Reflect(lastFrameVelocity.normalized, collisionNormal);
rb.velocity = direction * Mathf.Max(speed, minVelocity);
}
private void Fire()
{
s = true;
}
private void OnMouseDown()
{
Fire();
}
}
Answer by Ady_M · Jan 05, 2019 at 04:07 PM
First of all, move AddForce and the lastFrameVelocity assignment to FixedUpdate. The regular Update event is not suited for physics manipulation.
Secondly, if you need that much control over the physics then maybe you should consider enabling isKinematic on the Rigidbody and doing the collision detection yourself using Raycast.
Thirdly, and I'm sorry if this sounds pessimistic, but you should not rely on the physics engine that much. It cannot simulate the real world precisely. All it can do (due to performance) is approximate. So, if there is a great chance that the ball will hit the corner perfectly as shown in the image then I would advise you to check for this condition specifically. You could, for instance, check if the velocity.x is zero (assuming that's left/right) and the same with velocity.z, if there's a chance the ball might hit the corner horizontally, and check if the ball is lined up perfectly (or close enough) with the intersection.
Your answer
![](https://koobas.hobune.stream/wayback/20220612185143im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to check for collision between a moving kinematic object and an empty object? 3 Answers
How can I see my physics2d joints? 0 Answers
Colliders in a wall jut out 0 Answers
How can a character not move out of box collider's bounds? 1 Answer
Top Down 2d (PC): Gameobjects' Colliders intermeshing 1 Answer