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

translate object using onswipe in unity

I am trying to translate my sphere while swiping my finger on the screen.I want to swipe it only once,but for the below code I need to swipe again and again to move it forward,can anybody please tell me how to translate an object forward by swiping it only for once?!

`public float speed;

void FixedUpdate ()
{

//if (Input.touchCount >=1)
{
if (Input.touchCount > 0 &&
Input.GetTouch(0).phase == TouchPhase.Ended || (Input.GetMouseButtonDown(0)))
{

transform.Translate(Vector3.forward * Time.deltaTime*speed);
//transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}
}
}`

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.