Search Unity

Aiming object towards touch position with rigidbody on mobile.

Discussion in 'Physics' started by StephenRJudge27, Dec 11, 2018.

  1. StephenRJudge27

    StephenRJudge27

    Joined:
    Sep 2, 2015
    Posts:
    24
    Hey, I was wondering if there is a way to rotate an object to aim at your touch position on a phone while using rigidbody rotation physics? I have been able to do it with transform.right but it is causing issues with the movements I am using a rigidbody for.

    if (Input.touches.Length > 0) {
    Vector3 touchPosition = Input.GetTouch (0).position;
    Vector3 dir = GetWorldPositionOnPlane (touchPosition) - transform.position;
    transform.right = dir;
    }


    public Vector3 GetWorldPositionOnPlane(Vector3 screenPosition) {
    Ray ray = Camera.main.ScreenPointToRay (screenPosition);
    Plane xy = new Plane (Vector3.forward, new Vector3 (1,0, 0));
    float distance;
    xy.Raycast (ray, out distance);
    return ray.GetPoint (distance);
    }

    Basically how can I make this work with rigidbody rotation?
     
  2. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,195
    You can probably use a combination of RotateTowards, and Rigidbody.MoveRotation. Here's an excerpt of some code I use to align a rigidbody with an arbitrary vector (`desiredVector` in the code). You can probably use something similar, where you set desiredVector to the aim you want. This code goes in FixedUpdate.

    Code (CSharp):
    1.  
    2.             var angleBetween = Vector3.Angle(this.transform.up, desiredVector);
    3.  
    4.             if (angleBetween > 0.01f)
    5.             {
    6.                 // Rotate closer to the desired angle.
    7.  
    8.                 var desiredRot = Quaternion.FromToRotation(this.transform.up, desiredVector);
    9.    
    10.                 var maxNumberOfDegrees = Mathf.Min(20, 10 * Time.fixedDeltaTime * Mathf.Max(2, angleBetween / 2));
    11.  
    12.                 var rotateTo = Quaternion.RotateTowards(_rigidbody.rotation,
    13.                     desiredRot * _rigidbody.rotation,
    14.                     maxNumberOfDegrees);
    15.  
    16.                 _rigidbody.MoveRotation(rotateTo);
    17.             }
    18.  
     
    StephenRJudge27 likes this.
  3. N_Murray

    N_Murray

    Joined:
    Apr 1, 2015
    Posts:
    98
    Instead of ScreenToPointRay have you tried using ScreenToWorldPoint? That should hopefully give you a quick fix
     
    StephenRJudge27 likes this.