Search Unity

Continue Rigidbody2D path after "throwing" a GameObject

Discussion in '2D' started by Badams66, May 22, 2014.

  1. Badams66

    Badams66

    Joined:
    Mar 11, 2014
    Posts:
    49
    I'm using a script from a fellow Unity member that adds some multitouch features in a similar way the Mouse input functions work.
    The script works great, and I am able to drag my 2D rigidbody around the screen using the following code;

    Code (csharp):
    1.         void OnTouchDrag (Touch touch)
    2.         {
    3.                 currentScreenPoint = new Vector3 (touch.position.x, touch.position.y, screenPoint.z);
    4.                 pickedUp = true;
    5.         }
    and then in Update() is where I am moving the object to wherever the users finger is touching, updating frame by frame.
    Code (csharp):
    1. Update(){
    2. if (pickedUp) {
    3.                         verticalSpeed = rigidbody2D.velocity.y;
    4.                         horizontalSpeed = rigidbody2D.velocity.x;
    5.                         Debug.Log ("xspd: " + verticalSpeed + " / yspd: " + horizontalSpeed);
    6.                         gameObject.rigidbody2D.gravityScale = 0;
    7.                         screenPoint = Camera.main.WorldToScreenPoint (gameObject.transform.position);
    8.                         Vector3 currentPos = Camera.main.ScreenToWorldPoint (currentScreenPoint);
    9.                         transform.position = currentPos;
    10.                 }
    If the user drags their finger fast to "fling" the game object, I need the game object to maintain is course/speed and let gravity take over. I am setting the gravityscale to 0 while pickedUp is true, however when it becomes false then gravityScale returns to default. Everything works perfectly, and I actually have tested by adding AddForce when the object is released and the force is added.

    Basically, I just need to figure out how to determine the direction and amount of force to add based on the direction and how quickly the user is moving their finger.

    You can see in the above code, I added "verticalSpeed' and "horzontalSpeed" in hopes that Unity would be able to get the rigidbody velocity while being dragged then I could just add force based on this once the object is released, but the velocities always remain 0, im guessing due to the way I am moving the object.

    Hoping someone can shed some light on the best way to go about this!
     
    Last edited: May 22, 2014
  2. Badams66

    Badams66

    Joined:
    Mar 11, 2014
    Posts:
    49
    Had a thought today, thinking I could store the start coordinates and the end coordinates, and the amount of time between start and release, but if a user were to draw squiggly lines or something (other than a straight point to point), I dont think it would work well or give strange effects. Hoping someone has an idea! I cant be the only one looking for something like this lol