Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

C# 2D Ricochet Collision System

Discussion in 'Scripting' started by kenaochreous, Feb 10, 2015.

  1. kenaochreous

    kenaochreous

    Joined:
    Sep 7, 2012
    Posts:
    395
    I'm trying to come up with a 2D ricochet collision system but I'm having some trouble. After the collision has occured I want the gameobjects to gradually slow down and stop moving backwards so they can recover and keep moving. But rigidbody2D.AddForce(); keeps the gameobjects moving after the collision has occurred. Is there a way to implement Time.deltaTime to slow down rigidbody2D.AddForce();?

    Code (CSharp):
    1.        
    2. void OnCollisionEnter2D(Collision2D coll) {
    3.             coll.gameObject.rigidbody2D.AddForce(-transform.position * 100);
    4.             rigidbody2D.AddForce(transform.position * 100);
    5. }
    6.  
     
  2. Alanisaac

    Alanisaac

    Joined:
    Jan 25, 2015
    Posts:
    15
    It sounds like you want to model friction. Check out this UA post. Generally speaking, add a linear drag to your Rigidbody2D. If you have a specific surface/floor to model this on, you can add friction via a Physics2D material.
     
  3. kenaochreous

    kenaochreous

    Joined:
    Sep 7, 2012
    Posts:
    395
    It's top down so there is no surface. Just two gameobjects colliding with each other. So I assume I would want to add friction to the space around the gameobjects. Can you add friction this way? I'm also wondering if there are better ways of implementing the ricochet. Like maybe instead of rigidbody2D.AddForce(); I could invert the gameobject's direction upon collision instead since I don't want to add a ton of force.
     
  4. BenZed

    BenZed

    Joined:
    May 29, 2014
    Posts:
    524
    Add linearDrag. That creates friction in "the space aroud the gameobjects" as you put it.