Move an object in a circular path according to touch position
I am trying to move my object in this circular path with touch . I am trying to calculate first the angle between origin and touchpos , (all of my code in touchphase.moved block)
Vector3 touchPos = Camera.main.ScreenToWorldPoint (touch.position);
float angle = (Mathf.Abs (origin.y - touchPos.y) / Mathf.Abs (origin.x - touchPos.x));
if ((origin.y<touchPos.y && origin.x >touchPos.x)||(touchPos.y<origin.y && touchPos.x >origin.x)) {
angle*= -1;
}
angle = Mathf.Rad2Deg * Mathf.Atan(angle);
I think problem is here getting the angle .Then I am changing the position of the object like this :
float x = Mathf.Cos (angle) * 2f + origin.x;
float y = Mathf.Sin (angle) * 2f + origin.y;
toDragg.position = new Vector3 (x,y,0f);
Please help me somebody solving this problem . I have stuck here , tried to solve in many ways but no improvement .
Answer by doublemax · Oct 15, 2016 at 08:17 AM
You don't need any angles for this.
Vector3 v = touchPos - origin;
Vector3 new_pos = origin + v.normalized * circle_radius;
Thank you doublemax .Angle problem is solved . But there is another problem . it is not maintaining the radius .At different times different radius though I have used a constant value as circle-radius.
I forgot the "origin" in the second line. Although that shoudln't cause the effect you're describing.
@doublemax @OrajokNor The object is maintaining finger position rather than maintaining the radius.
public Transform origin; // origin publicaly in Editor float circle_radius = 3; // for maintaining the radius
void Update()
{
if ((Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.$$anonymous$$oved))
{
Vector3 touchPos = Camera.main.ScreenToWorldPoint (Input.GetTouch(0).position);
Vector3 v = touchPos - origin.position;
Vector3 new_pos = origin.position + (v.normalized * circle_radius);
transform.position = new_pos;
}
}