Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Throw object in direction of swipe in AR

Discussion in 'AR' started by gtramnull, Jun 17, 2020.

  1. gtramnull

    gtramnull

    Joined:
    Apr 23, 2020
    Posts:
    5
    Greetings,

    So I'm working on this small AR mobile project where it's basically got the same functionality as paper toss/pokemon go regarding throwing an object with touch/swipe.

    I got to the point where I manage to throw an object forward relative to the object's transform.forward. However, my intent is to apply force using .AddForce() toward the swipe direction but here's where I'm stuck at though. After some research I learned that I could use Camera.main.ScreenToWorldPoint() but that's causing an issue that whenever I move the camera to a different direction it seems as though the object gets thrown to the direction the camera was facing initially, potentially at startup. For example, app starts, I throw the object, it works fine but if I turn the camera/mobile device 180º the object gets thrown backwards.

    Here's the code snippet:

    Code (CSharp):
    1. private void Throw() {
    2.         touchEndPosition.z = transform.position.z;
    3.         var direction = Camera.main.ScreenToWorldPoint(touchEndPosition);
    4.  
    5.         rb.AddForce(direction * force);
    6. }
    Now I'm wondering if ScreenToWorldPoint() is even applicable in an AR scenario...


    Any help is much appreciated!
     
  2. KyryloKuzyk

    KyryloKuzyk

    Joined:
    Nov 4, 2013
    Posts:
    1,128
    You're not taking a touch position but a Z position of your transform.
    To take a touch position you can use Input.GetMouseButtonUp(0). It works for touch input perfectly if your app doesn't require multi-touch.

    void Update() {
    if (UnityEngine.Input.GetMouseButtonUp(0)) {
    var touchEndPosition = UnityEngine.Input.mousePosition;
    }
    }