- Home /
C# Projectile Ricochet After Collision2d
I'm trying to get my projectiles to ricochet after they collide with a gameobject. I tried GetComponent().velocity = -GetComponent().velocity; and GetComponent().AddForce(-GetComponent().velocity * Time.deltaTime); but neither worked. Am I doing something wrong?
void Update (){
GetComponent<Rigidbody2D>().velocity = transform.up * speed;
}
void OnCollisionEnter2D(Collision2D other){
//GetComponent<Rigidbody2D> = -GetComponent<Rigidbody2D>;
GetComponent<Rigidbody2D>().AddForce(-GetComponent<Rigidbody2D>().velocity * Time.deltaTime);
}
Answer by xortrox · May 14, 2015 at 10:03 AM
First of all, googling your question title "projectile ricochet unity" brings up some useful articles that explain the matter in mainly 3D but this should be easy to convert into 2D. Altough the unity documentation might be an ven simpler solution: Collision2D
I believe that Collision2D.relativeVelocity might be something you could look in to.
Over to your script:
GetComponent<Rigidbody2D>().AddForce(-GetComponent<Rigidbody2D>().velocity * Time.deltaTime);
The result of this is that for the time of the frame of the collision only, you add force based on the rigidbody velocity. Basically if your object was moving at a velocity of (2.0f, 2.0f) and your FPS was at 60, you would have a Time.deltaTime value of 1000/60 = 16.67 ms 16.67 / 1000 = 0.016f
So the velocity would end up negative as you've declared it to be, but it would be multiplied by 0.016f, (0.016f * 2.0f) resulting in (-0,032f, -0,032f) as the new velocity.
So depending on your ricochet type (if it should not bounce off the wall based on angles and just ricochet straigth back) you should only have to do this in your script:
GetComponent<Rigidbody2D>().velocity = -GetComponent<Rigidbody2D>().velocity;
//Or the more optimized version I think
GetComponent<Rigidbody2D>().velocity *= -1.0f;
Also a side note, you should probably reference Rigidbody2D at the start of your script so you don't have every bullet calling GetComponent when they collide, this could lead to some overhead I've heard.
public Rigidbody2D Rigidbody2D;
void Start()
{
Rigidbody2D = GetComponent<Rigidbody2D>();
}
Then later you could do something like this:
void OnCollisionEnter2D(Collision2D other)
{
Rigidbody2D.velocity *= -1.0f;
}
If you want a bullet that ricochets based on impact angle then this would not be the solution.