Search Unity

Swipe to AddForce to RigidBody in specific direction.

Discussion in 'Scripting' started by stahlbrand1997, Apr 8, 2021.

  1. stahlbrand1997

    stahlbrand1997

    Joined:
    Nov 20, 2018
    Posts:
    11
    Hello everybody,
    I'm trying to make a ball be sent away in the direction you swipe after your finger has travelled 40 pixels using the public float swipeRange. Unfortunately my ball just sits still and don't react to my swipes. Any ideas?
    Appreciate any help.


    public class Swipe2 : MonoBehaviour
    {
    public float swipeRange;
    private Vector2 currentPosition;

    Vector2 startPos, endPos, direction; // touch start position, touch end position, swipe direction

    [SerializeField]
    float throwForceInXandY = 1f; // to control throw force in X and Y directions

    [SerializeField]
    float throwForceInX = 50f; // to control throw force in Z direction

    Rigidbody rb;

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

    // Update is called once per frame
    void Update()
    {

    // if you touch the screen
    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
    {

    // getting touch position and marking time when you touch the screen
    startPos = Input.GetTouch(0).position;

    //before it was } here. not at end

    if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved)
    {

    currentPosition = Input.GetTouch(0).position;

    Vector2 Distance = currentPosition - startPos;
    // getting release finger position

    if (Distance.magnitude > swipeRange)
    {
    //endPos = Input.GetTouch(0).position;
    // calculating swipe direction in 2D space
    direction = startPos - currentPosition;

    // add force to balls rigidbody in 3D space depending on swipe time, direction and throw forces
    rb.AddForce(-direction.x * throwForceInXandY, -direction.y * throwForceInXandY, 0);

    // Destroy ball in 4 seconds
    Destroy(gameObject, 3f);

    }

    }
    }
    }
    }
     
  2. Stevens-R-Miller

    Stevens-R-Miller

    Joined:
    Oct 20, 2017
    Posts:
    677
    Joe-Censored likes this.