Move to closest touch (android);

Hi,

I’m trying to make my characters find the closest touch and then move to it.

I’ve tried but they will still only move to the first touch and ignore the 2nd until the 1st touch is over.

Here is my code:

for (var i = 0; i < Input.touchCount; ++i) 
	{
		var touch = Input.GetTouch(i);
		if (touch.phase != TouchPhase.Ended && touch.phase != TouchPhase.Canceled) 
		{
			var fingerPos =  Input.GetTouch(i).position;
			var pos : Vector3 = fingerPos;
   			pos.z = 10;
    		var realWorldPos = Camera.main.ScreenToWorldPoint(pos);
			
			var closest : Vector3; 
			var distance = Mathf.Infinity; 
			var position = transform.position; 
			
			var diff = (realWorldPos - position);
			var curDistance = diff.sqrMagnitude; 
			if (curDistance < distance)
			{ 
				closest = realWorldPos; 
				distance = curDistance; 
			} 
			
			
			this.GetComponent(AIMovement).action = this.GetComponent(AIMovement).action.moveToFinger;
			this.GetComponent(AIMovement).target = closest;			
		}
		
		if(touch.phase == TouchPhase.Ended)
		{
			this.GetComponent(AIMovement).action = this.GetComponent(AIMovement).action.wander;
		}

I’ve looked all over the internet and can’t find anything.

Any help would be MUCH appreciated!

Thanks

I solved it!

here’s the code in case anyone else wants to know…

if(Input.touchCount > 0)
	{					
		var touch1 = Input.GetTouch(0);
		if (touch1.phase != TouchPhase.Ended && touch1.phase != TouchPhase.Canceled) 
		{
			var pos1 = Camera.main.ScreenToWorldPoint(touch1.position);					
		}
		if(touch1.phase == TouchPhase.Ended)
		{			
			pos1 = Vector3(999,999,999);
			this.GetComponent(AIMovement).action = this.GetComponent(AIMovement).action.wander;			
		}		
		
		if(Input.touchCount == 0)
		{
			this.GetComponent(AIMovement).action = this.GetComponent(AIMovement).action.moveToFinger;
			this.GetComponent(AIMovement).target = pos1;
		}	
	}
		
	if(Input.touchCount > 1)
	{
		var touch2 = Input.GetTouch(1);
		if (touch2.phase != TouchPhase.Ended && touch2.phase != TouchPhase.Canceled) 
		{
			var pos2 = Camera.main.ScreenToWorldPoint(touch2.position);					
		}
		if(touch2.phase == TouchPhase.Ended)
		{
			pos2 = Vector3(999,999,999);
			this.GetComponent(AIMovement).action = this.GetComponent(AIMovement).action.wander;			
		}	
		
		
		posArray = [pos1,pos2];	
		var closest : Vector3; 
		var distance = Mathf.Infinity; 
		var position = transform.position; 
		// Iterate through them and find the closest one
		for (var go : Vector3 in posArray)  
		{ 
			var diff = (go - position);
			var curDistance = diff.sqrMagnitude; 
			if (curDistance < distance)
				{ 
					closest = go; 
					distance = curDistance; 
				} 
		}
		
		this.GetComponent(AIMovement).action = this.GetComponent(AIMovement).action.moveToFinger;
		this.GetComponent(AIMovement).target = closest;		
	}