简体   繁体   中英

Unity C# TouchScript - Moving an object to direction of Flick

I'm trying to get an object to read the flick (using the Touchscript package on Unity) - then flick the object which the script is attached to in the direction.

It definitely reads the flick, but I have no idea how to read/obtain the direction to add the force onto the rigidbody/translate it in the direction. I looked at the references such as ScreenFlickVector & GestureDirection with no luck. I would love your help!

private Rigidbody rb;
    // Use this for initialization
    void Start () {
        rb= GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        transform.Translate(Vector3.down * Time.deltaTime);

    }

    private void OnEnable()
    {
        // subscribe to gesture's Tapped event
        GetComponent<FlickGesture>().Flicked += OnFlick;

    }
    private void OnDisable()
    {
        GetComponent<FlickGesture>().Flicked -= OnFlick;
    }

    private void OnFlick(object sender, EventArgs e)
    {
        // Implement the Flick

    }
}

Accessing the FlickGesture info can be done like this:

void OnFlick(object sender, System.EventArgs e)
{
    var gesture = sender as FlickGesture;

    float distanceFromCamera = Vector3.Distance(transform.position, Camera.main.transform.position);

    Vector3 wp1 = new Vector3(gesture.PreviousScreenPosition.x, gesture.PreviousScreenPosition.y, distanceFromCamera);
    wp1 = Camera.main.ScreenToWorldPoint(wp1);

    Vector3 wp2 = new Vector3(gesture.ScreenPosition.x, gesture.ScreenPosition.y, distanceFromCamera);
    wp2 = Camera.main.ScreenToWorldPoint(wp2);

    Vector3 velocity = (wp2 - wp1) / gesture.FlickTime;

    rigidbody.AddForce(velocity, ForceMode.VelocityChange);
}

By taking the start and end positions of the gesture and converting those positions into world space, then applying a scaling with the elapsed gesture time results in the world space velocity of the object being flicked.

I hope this gets you on your way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM