Search Unity

How to slice rigidbodies?

Discussion in 'Physics' started by greenLantern101, Jan 1, 2015.

  1. greenLantern101

    greenLantern101

    Joined:
    Jan 1, 2015
    Posts:
    31
    I have a crate in my 2D game, made of a 2D rigidbody and a box collider. How can i make a player be able to slice it with a laser, so that the result will be 2 separate rigidbodies?
     
    Last edited: Jan 2, 2015
  2. medvedya2012

    medvedya2012

    Joined:
    May 27, 2014
    Posts:
    41
    You have to convert your collider to lines after that you find point of intersection laser with lines. Then you will be able create two or more polygon colliders.
    I guess, you use sprite renderer. You may convert your sprite to mesh, and slice mesh like slice collider and do triangulation.
    Code (CSharp):
    1. public static bool intersection(Vector2 a1, Vector2 a2, Vector2 b1, Vector2 b2, out Vector2 point)
    2.         {
    3.             point = Vector2.zero;
    4.  
    5.             float x1 = a1.x;
    6.             float y1 = a1.y;
    7.             float x2 = a2.x;
    8.             float y2 = a2.y;
    9.             float x3 = b1.x;
    10.             float y3 = b1.y;
    11.             float x4 = b2.x;
    12.             float y4 = b2.y;
    13.             float t = 0;
    14.             float xa = 0;
    15.             float ya = 0;
    16.             if (Mathf.Abs((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)) < 0.0001)
    17.             {
    18.                 return false;
    19.             }
    20.             else
    21.             {
    22.                 t = ((y3 - y1) * (x3 - x4) - (x3 - x1) * (y3 - y4)) / ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4));
    23.                 if ((t >= 0) && (t <= 1))
    24.                 {
    25.                     xa = x1 + t * (x2 - x1);
    26.                     ya = y1 + t * (y2 - y1);
    27.                     if (((x3 - xa) * (x4 - xa) <= 0) && ((y3 - ya) * (y4 - ya) <= 0))
    28.                     {
    29.  
    30.                         point = new Vector2(xa, ya);
    31.                         return true;
    32.                     }
    33.                     else
    34.                     {
    35.                         return false;
    36.                     }
    37.                 }
    38.                 else
    39.                 {
    40.                     return false;
    41.  
    42.                 }
    43.             }
    44.         }
     
    greenLantern101 likes this.
  3. greenLantern101

    greenLantern101

    Joined:
    Jan 1, 2015
    Posts:
    31
    Thanks for taking the time to write all that :)