alter ego alter ego - 1 month ago 9
C# Question

Translate object by swiping in Unity

I am trying to translate my sphere while swiping my finger on the screen.

With the code below I need to swipe again and again to move it forward.
How can I translate an object forward by swiping only once?

public float speed;

void FixedUpdate ()
{
if (Input.touchCount > 0 &&
Input.GetTouch(0).phase == TouchPhase.Ended || (Input.GetMouseButtonDown(0)))
{
transform.Translate(Vector3.forward * Time.deltaTime*speed);
}
}

Answer

Your code makes the object move for the exact moment when the TouchPhase has Ended. In order to push the object, try applying a force.

Modified C# example from Unity Tutorials:

public float speed;
public Rigidbody rb;

void Start() 
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate() 
{
    if (Input.touchCount > 0 &&
        Input.GetTouch(0).phase == TouchPhase.Ended || (Input.GetMouseButtonDown(0)))
    {
        rb.AddForce(Vector3.forward * Time.deltaTime * speed);
    }
}

You need to add a Rigidbody3D Component to the object, if you use this technique.