Search Unity

Calculate the distance for activate a rigidbody

Discussion in 'Physics' started by stylophone, Aug 30, 2018.

  1. stylophone

    stylophone

    Joined:
    Aug 16, 2012
    Posts:
    37
    Hi community, I'm currently working on my physics game and in my game, I need to change the character's movement speed but always keep a rigidbody falling in just front of it. For example:


    Code (CSharp):
    1. public class Test : MonoBehaviour
    2. {
    3.     public Transform cube1;
    4.     public Transform cube2;
    5.  
    6.     public float activeDist = 4.0f;
    7.     public float speed = 2.0f;
    8.  
    9.     private void Update()
    10.     {
    11.         cube1.Translate(Vector3.right * Time.deltaTime * speed);
    12.         float currentDist = (cube2.position - cube1.position).sqrMagnitude;
    13.  
    14.         if (currentDist < activeDist * activeDist)
    15.         {
    16.             if (cube2.GetComponent<Rigidbody>().isKinematic)
    17.             {
    18.                 cube2.GetComponent<Rigidbody>().isKinematic = false;
    19.             }
    20.         }
    21.     }
    22. }
    I'm not an expert in physics calculation. Let's say the current movement speed and the active distance works just fine. How can I calculate the activate distance for different movement speed but achieve the same result? And without changing the gravity. Thanks for any help.
     
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,778
    Interesting problem
    If I get you right, you want blue object fall just before red, if in the range.

    I would approach it this way.
    - Get vertical distance of blue object.
    - Calculate duration of fall, based on gravity.
    Knowing the duration
    - Calculate velocity of red object
    - Calculate distance to travel by red object,
    within fall duration of blue object.
    - Calculate distance from red object to drop point of blue object (in 2D that is just single axis (right))
    - Calculate difference between drop point distance and distance to travel withing fall duration.
    - You may need add extra offset velocity, to the calculated difference, to ensure blue box falls ahead the red one.
    Then
    - If difference with offset is 0, drop the blue object.

    For first two parts, check out this link with simple equations
    https://en.wikipedia.org/wiki/Equations_for_a_falling_body

    upload_2018-8-31_15-38-36.png