Search Unity

Flick Gesture using RB2D velocity moves toward Anchor

Discussion in 'Scripting' started by beanie4now, Dec 6, 2018.

  1. beanie4now

    beanie4now

    Joined:
    Apr 22, 2018
    Posts:
    311
    I'm creating a netflix like slide/ flick browsing menu. I have a "Category" bar with many buttons on it that i am attempting to slide with the following.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class TouchSlider : MonoBehaviour {
    4.     private float start;
    5.     private float end;
    6.     private Rigidbody2D rb;
    7.     private void Awake()
    8.     {
    9.         move = false;
    10.         rb = GetComponent<Rigidbody2D>();
    11.        
    12.         start = 0;
    13.         end = start;
    14.     }
    15.  
    16.     private void OnMouseOver()
    17.     {
    18.    
    19.         if (Input.GetMouseButton(0))
    20.         {
    21.            
    22.             Vector3 mouse = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    23.             start = mouse.x;
    24.             rb.velocity += new Vector2(start - end, 0);
    25.  
    26.             end = start;
    27.  
    28.         }
    29.     }
    30. }
    If I just hold my finger on the slider bar it will align the anchor to my finger...
    I'm not grasping why this is happening.
     
  2. beanie4now

    beanie4now

    Joined:
    Apr 22, 2018
    Posts:
    311
    I figured out a solution:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class TouchSlider : MonoBehaviour {
    4.     private bool move;
    5.     private float start;
    6.     private float end;
    7.     private Rigidbody2D rb;
    8.     private void Awake()
    9.     {
    10.         move = false;
    11.         rb = GetComponent<Rigidbody2D>();
    12.         start = 0;
    13.         end = start;
    14.     }
    15.  
    16.     private void OnMouseOver()
    17.     {
    18.         if(Input.GetMouseButtonDown(0))
    19.         {
    20.             Vector3 mouse = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    21.             end = mouse.x;
    22.             move = true;
    23.         }
    24.         if (Input.GetMouseButton(0))
    25.         {
    26.             Vector3 mouse = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    27.             start = mouse.x;
    28.             rb.velocity = new Vector2( Mathf.Clamp( (start - end)* 4,-10,10), 0);
    29.         }
    30.     }
    31. }