- Home /
How do I get velocity from a collision?
I am simply trying to get the velocity that an object collides with, so that it can inherit that velocity. I am new to scripting.
Basically I have a ball and two paddles (imagine something 2D like pong with similar graphics but you can move closer and farther away). If the player charges towards the ball while the paddle is moving in, the ball will pass right through it and not bounce off. This causes the ball to slow down to a crawl.
If there is an easier way to do achieve this please let me know.
Answer by AlbieMorrison · Sep 03, 2021 at 12:45 PM
You can get the relative velocity between the two colliding objects and bounce the ball back by doing this, in the script that controls the ball:
void Start()
{
Rigidbody2D rb = GetComponent<Rigidbody2D>();
}
OnCollisionEnter2D(Collision2D collision)
{
Vector2 velocity = collision.relativeVelocity;
rb.velocity = Vector2.Reflect(velocity,Vector2.right/*make this a Vector2 pointing 90 degrees from your paddle surface*/);
}
Also make sure you have a Rigidbody2D on at least the ball and probably both paddles as well, with the appropriate colliders for their shapes. I believe you will need to freeze the rotation and position in all directions of the Rigidbodies. Hopefully this helps!
I have never heard of Reflect before. Can you explain what this means from the manual? https://docs.unity3d.com/ScriptReference/Vector2.Reflect.html
public static Vector2 Reflect(Vector2 inDirection, Vector2 inNormal);
What is inDirection and what is inNormal? Thank you.
inDirection would be the velocity vector of the object co$$anonymous$$g into the collision, and inNormal would be the vector pointing perpendicular to the surface of the collision (also known as the normal)
Vector2.Reflect()
takes a vector and reflects it around the isNormal
vector, using the inDirection
vector as the vector to reflect. So effectively, whatever the angle between the two vectors, it takes that and returns a new vector with the same angle away from isNormal
only on the opposite side.
Your answer
Follow this Question
Related Questions
How do I increase forward velocity of a 2D ball when it bounces? 1 Answer
Physics in 2d arkanoid. Tangential and normal velocity 1 Answer
Velocity Movement & Physics Interactions by Rigidbody2D 0 Answers
How can I make 2D movement less jerky on a controller, with velocity and such? 0 Answers
Inconsistent Rigidbody2D velocity. 0 Answers