- Home /
Move from A to B after recieving touch input
I have been trying to get an object to move from A to B in a set period of time after the player touches the screen. I've looked at various examples however whenever I try to add touch input it doesn't quite work properly and consecutive inputs after the first touch effect the movement. Does anyone know how I could achieve this?
Answer by CatFisting · Dec 03, 2017 at 10:17 PM
It's important whether you're using C# or JS, but in C# I'd do it a bit like this.
public GameObject object;
bool hasTouched = false;
Vector3 A;
Vector3 B;
Vector3 distance;
void Start(){
A = [A VECTOR3 COORDINATES HERE]
B = [B VECTOR3 COORDINATES HERE]
distance = A - B;
}
void Update(){
if (Input.touchCount > 0 && hasTouched == false){
//do your moving here with an IEnumerator loop
hasTouched = true;
}
}
Thank you very much for responding with this code, this works well for receiving the touch input. However I tried adding the IEnumerator loop but couldn't get it to work as I am very new to scripting, would it be possible to give an example or link me to something that I could add to the code to make it work.
If it works well I assume it's already moving as you want it but the ti$$anonymous$$g is off. An IEnumerator will work off of a WaitForSeconds method to know how many times to go before repeating. Here's an IEnumerator example.
private IEnumerator example(float
time){
//do something small once
yield return new WaitForSeconds(time);
}
Call it somewhere earlier in the script with StartCoroutine(example (.5f));
You could repeat it a certain number if times using a basic 'for loop'.
Thank you so much for the example. I have now managed to get the IEnumerator working and have implemented it into my game with the touch input and it all functions as intended.
Your answer
![](https://koobas.hobune.stream/wayback/20220612143913im_/https://answers.unity.com/themes/thub/images/avi.jpg)