Search Unity

Question How can I reset the rigidbody's rotation in Update()

Discussion in 'Physics' started by realmcrafter, Dec 14, 2020.

  1. realmcrafter

    realmcrafter

    Joined:
    Nov 12, 2020
    Posts:
    7
    I'm creating an AR game in Unity where the player can throw an object.

    The problem is that the object can only be thrown in the direction of where the camera is aimed at the start of the application. So after loading the object and throwing it, it doesn't matter where I stand with my device. Even when I turn arround with my device, the ball will instead of going forward be thrown at me while swiping my finger forward.

    So I guess I can achieve this by resetting the rigidbody's rotation per frame.. What is the correct way of doing this?

    SwipeScript.cs
    Code (CSharp):
    1. Vector2 startPos, endPos, direction; // touch start position, touch end position, swipe direction
    2. float touchTimeStart, touchTimeFinish, timeInterval; // to calculate swipe time to sontrol throw force in Z direction
    3.  
    4. [SerializeField]
    5. float throwForceInXandY = 1f; // to control throw force in X and Y directions
    6.  
    7. [SerializeField]
    8. float throwForceInZ = 50f; // to control throw force in Z direction
    9.  
    10. Rigidbody rb;
    11.  
    12. void Start()
    13. {
    14.     rb = GetComponent<Rigidbody> ();
    15. }
    16.  
    17. // Update is called once per frame
    18. void Update () {
    19.  
    20.     // if you touch the screen
    21.     if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) {
    22.  
    23.         // getting touch position and marking time when you touch the screen
    24.         touchTimeStart = Time.time;
    25.         startPos = Input.GetTouch (0).position;
    26.     }
    27.  
    28.     // if you release your finger
    29.     if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Ended) {
    30.  
    31.         // marking time when you release it
    32.         touchTimeFinish = Time.time;
    33.  
    34.         // calculate swipe time interval
    35.         timeInterval = touchTimeFinish - touchTimeStart;
    36.  
    37.         // getting release finger position
    38.         endPos = Input.GetTouch (0).position;
    39.  
    40.         // calculating swipe direction in 2D space
    41.         direction = startPos - endPos;
    42.  
    43.         // add force to balls rigidbody in 3D space depending on swipe time, direction and throw forces
    44.         rb.isKinematic = false;
    45.         rb.AddForce (- direction.x * throwForceInXandY, - direction.y * throwForceInXandY, throwForceInZ / timeInterval);
    46.  
    47.         // Destroy ball in 4 seconds
    48.         Destroy (gameObject, 3f);
    49.  
    50.     }          
    51. }