I am trying to create a 3d game in unity. I have a cube in unity and I want it to move left or right on swipe . It should move to a distance till where user swipe or take their finger off of a screen. I want it to move fast or the cube should move fast on swipe and cube should flow smooth. Like in the gif there is a circle and the user use their finger to move the circle till wherever the user swipe it and it should be instant and I want my cube to move like that at a distance till where user swipe their finger and it should be instant and fast. I don't know how to do it. Any help is appreciated!
Answer
Here is an example script to answer your question:
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0); // get first touch since touch count is greater than zero
if (touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved)
{
// get the touch position from the screen touch to world point
Vector3 touchedPos = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10));
// lerp and set the position of the current object to that of the touch, but smoothly over time.
transform.position = Vector3.Lerp(transform.position, touchedPos, Time.deltaTime);
}
}
Basically, when this is attached to the object you want to move (this is for 2d objects, though it can be tweaked for 3d), it gets the touch location and moves itself to that spot. Hope this helps!
EDIT:
You can tweak for 3d by changing the value of your object's Z axis. Example:
Camera.main.WorldToScreenPoint(touch.position.x, touch.position.y,transform.position.z)
No comments:
Post a Comment