- Home /
Moving object smoothly to touch location
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);
}
}
}
This article by The Game Contriver helped me solve this... $$anonymous$$ove Object To Tap/Click Position
Awesome! I tried to find solution over 24 hours until I found this. Thank you!
Answer by meat5000 · Oct 29, 2013 at 12:51 PM
Firstly, you are feeding screen coordinates in to your Lerp.
Try the ScreenToWorldPoint and other camera functions. Use it to convert a screen position into a world space coordinate.
Secondly, you use Lerp incorrectly. the t factor only works between 0 and 1. 0 Represents to 'from' field, 1 represents the 'to' field and values between 0->1 return a point between from and to. As you have t set to 5 it will simply return the 'to' value straight away as anything >1 is read as 1.
Ok I think I implemented your answer but the same problem still occurs. Could you take a look at my edit and tell me if I'm doing something wrong?
Its because you are telling the object to follow touch posiiton, XYZ, since you are 2D you must delete an axis.
But I include 0 as the z-position to make it a Vector3 so that should not be a problem right? Do you mean I should use transform.position = Vector2.Lerp(transform.position, touch.position, Time.deltaTime)
? I'm using that now but the same problem still occurs. And any ideas on how to use ScreenToWorldPoint with a Vector2?
touch.position is in screen space. Use the function I linked to retrieve the world space position underneath the screen position.