A couple of days ago I’ve started learning how to use Unity for mobile games. In order to do that I’m trying to make a simple game in which a cube moves smoothly to wherever the user touches the screen. I came up with the following code:
public float speed = 0.02f;
void Update () {
if (Input.touchCount > 0) {
if (Input.GetTouch(0).phase == TouchPhase.Stationary || Input.GetTouch(0).phase == TouchPhase.Moved) {
// Move cube smoothly to touch location
transform.position = Vector3.Lerp(transform.position, new Vector3(Input.GetTouch(0).position.x * speed, Input.GetTouch(0).position.y * speed, 0), 5);
}
}
}
However, when I touch the screen the cube simply disappears. I presume its moving to a location off screen but I don’t understand why. I’ve been searching around for an answer for a while now but I can’t seem to find any good solutions.
EDIT:
So I found the solution and its working perfectly. For anybody with the same problem:
void Update () {
if (Input.touchCount > 0) {
// The screen has been touched so store the touch
Touch touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved) {
// If the finger is on the screen, move the object smoothly to the touch position
Vector3 touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10));
transform.position = Vector3.Lerp(transform.position, touchPosition, Time.deltaTime);
}
}
}