- Home /
How to compare position values in Input table
Hi, In my application I locate the position of the screen touches. I would like to calculate the distance between touches by comparing each one and if say the distance is more than 300 pixels then display an image or do some action. Currently I am able to compare two positions between each other but I don't know how to do it for all positions, that is whenever a new touch appears compare it with previous ones if the distance is not more than 300.
using UnityEngine;
using UnityEngine.UI;
public class TouchPosition : MonoBehaviour
{
public Text distanceText;
public float distance;
void Update()
{
CheckDistance();
}
public void CheckDistance()
{
foreach (Touch touch in Input.touches)
{
for(int i = 0; i < Input.touchCount; i++)
{
Vector2 touchPosition = Input.touches[i].position;
if(i > 1)
{
float positionDistance;
Vector2 touchPosition2 = Input.touches[i-1].position;
positionDistance = Vector2.Distance(touchPosition, touchPosition2);
distanceText.text = " Distance : " + positionDistance;
}
}
}
}
}
Answer by Firnox · Feb 03 at 08:32 PM
In your code you're iterating over the touches in the foreach loop but then not actually using the touch variable at all. I think you realise you need a double loop but you just haven't implemented it correctly. Is something like this what you're looking for?
using UnityEngine;
public class TouchPosition : MonoBehaviour {
public float distance;
void Update() {
CheckDistance();
}
public void CheckDistance() {
// You can start this loop from 1 because if you only have 1 touch there's nothing to do.
for (int i = 1; i < Input.touchCount; i++) {
// Loop over other touches upto but not including this one
for (int j = 0; j < i; j++) {
float dist = Vector2.Distance(Input.touches[i].position, Input.touches[j].position);
Debug.Log($"Dist between touch {i} and {j} = {dist}");
}
}
}
}
This is partly what I was looking for because with your proposed solution I am comparing a new touch with a previous touch - and how to make it compare each new touch with each previous touch? Not just the last one. More clearly: compare the distance between, for example, the fourth touch with the first, second, and third. If distance = 100 then something
My code snippet will compare with all the previous touches. For example if you have 4 touches then you get:
i = 1 (j = 0) Compares touch 1 with touch 0
i = 2 (j = 0, 1) Compares touch 2 with touches 0, 1
i = 3 (j = 0, 1, 2) Compares touch 3 with touches 0, 1, 2
That gives you each of the pairs of touches. (0,1), (0,2), (0,3), (1,2), (1,3), (2,3). I believe this is what you're asking for?
Your answer
Follow this Question
Related Questions
Can't see the angle value on the screen 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity TUIO & 2D Barcodes 1 Answer
Position in Vector (C#) 1 Answer