0

I have a script that can detect a swipe, L or R direction and report. But I cannot find or figure out how to integrate a block that can detect if the swipe occurred over the/an object with a Box Collider 2D. Seems like it would be fairly straight forward: In Update, report if mouse/finger intersects Collider of object, set variable 'validSwipe to true', etc.

Is for a simple 2D Unity game. Ideally, the swipe must pass over an object on screen to be considered 'valid' and trigger an event. To test, I have it print feedback onscreen.

using UnityEngine;

public class Swipe : MonoBehaviour
{
private bool isMouseDown;
private bool isMouseOver;
private bool isSwipedRight;
private bool isSwipedLeft;
private Vector2 swipeStartPos;
private Renderer objectRenderer;
private Color originalColor;
private Color swipeColor = Color.green;
private float swipeDuration = 1f;
private float swipeTimer;
private GUIStyle guiStyle = new GUIStyle();

    void Start()
    {
        // renderer component attached to the game object
        objectRenderer = GetComponent<Renderer>();
        // Store the original color of the object
        originalColor = objectRenderer.material.color;
    }
    
    void Update()
    
    {
        // If the object has been swiped, set its color to the swipe color for the duration of swipeDuration
        if (isSwipedRight)
        {
            objectRenderer.material.color = swipeColor;
            swipeTimer += Time.deltaTime;
            if (swipeTimer >= swipeDuration)
            {
                objectRenderer.material.color = originalColor;
                swipeTimer = 0f;
                isSwipedRight = false;
            }
        }
        else if (isSwipedLeft)
        {
            objectRenderer.material.color = swipeColor;
            swipeTimer += Time.deltaTime;
            if (swipeTimer >= swipeDuration)
            {
                objectRenderer.material.color = originalColor;
                swipeTimer = 0f;
                isSwipedLeft = false;
            }
        }
        // Otherwise, reset its color to the original color
        else
        {
            objectRenderer.material.color = originalColor;
        }
    
        // Check if the left mouse button is pressed down
        if (Input.GetMouseButtonDown(0))
        {
            // Set the isMouseDown flag to true
            isMouseDown = true;
            // Store the position of the mouse
            swipeStartPos = Input.mousePosition;
            // Reset the swipe flags
            isSwipedRight = false;
            isSwipedLeft = false;
        }
    
       
        if (Input.GetMouseButtonUp(0))
        {
            // Reset the isMouseDown and isMouseOver flags
            isMouseDown = false;
            isMouseOver = false;
    
            // Calculate the distance between the start and end positions of the swipe
            Vector2 swipeEndPos = Input.mousePosition;
            float swipeDistance = swipeEndPos.x - swipeStartPos.x;
    
            // Check if the swipe went across the object and was long enough to be considered a swipe
            if (Mathf.Abs(swipeDistance) >= objectRenderer.bounds.size.x && Mathf.Abs(swipeDistance) >= Screen.width / 12)
            {
                // Set the appropriate swipe flag based on the direction of the swipe
                if (swipeDistance > 0)
                {
                    isSwipedRight = true;
                }
                else
                {
                    isSwipedLeft = true;
                }
            }
        }
    }
    
    void OnGUI()
    {
        // If a rightward swipe was detected, display a large red 'R' in the center of the screen for the duration of swipeDuration
        if (isSwipedRight)
        {
            guiStyle.fontSize = 100;
            guiStyle.normal.textColor = Color.red;
            GUI.Label(new Rect(Screen.width / 2 - 50, Screen.height / 2 - 50, 100, 100), "R", guiStyle);
        }
        // If a leftward swipe was detected, display a large blue 'L' in the center of the screen for the duration of swipeDuration
        else if (isSwipedLeft)
        {
            guiStyle.fontSize = 100;
            guiStyle.normal.textColor = Color.blue;
            GUI.Label(new Rect(Screen.width / 2 - 50, Screen.height / 2 - 50, 100, 100), "L", guiStyle);
        }
    }

}

2 Answers2

0

You can use MonoBehaviour.OnMouseOver() event function on the BoxCollider2D that you are trying to check. Create a new script for it and add

private void OnMouseOver()
{
    mouseOver = true;
}

private void OnMouseExit()
{
    mouseOver = false;
}

on it to check for mouse being over it

Eugen1344
  • 165
  • 3
  • 17
0

This script works. Uses Physics2D.LinecastAll to check the line between two points after the swipe has concluded.

using UnityEngine;

public class Swipe_A : MonoBehaviour
{
    private bool validSwipe = false;
    private Vector2 startPosition;
    private Vector2 endPosition;

    void Update()
    {
        //mark start and end of swipe
        if (Input.GetMouseButtonDown(0))
        {
            startPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        }

        if (Input.GetMouseButtonUp(0))
        {
            endPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

            DetermineSwipe();
        }
    }

    private void DetermineSwipe()
    {
        float swipeMagnitude = (endPosition - startPosition).magnitude;//How long was the swipe
        if (swipeMagnitude > 0.3f)//If the swipe is this long

        {

            Vector2 swipeStart = startPosition;
            Vector2 swipeEnd = endPosition;

            // Perform a linecast to check for colliders along the entire line of the swipe after the swipe
            RaycastHit2D[] hitResults = Physics2D.LinecastAll(swipeStart, swipeEnd);
            if (hitResults.Length > 0)

            {
                validSwipe = true;
                Debug.Log("Over Object");
            }
            else
            {
                validSwipe = false;
                Debug.Log("Miss");
            }

            if ((endPosition.x > startPosition.x) && validSwipe)
            {
                Debug.Log("R_Swipe");
            }
            else if ((endPosition.x < startPosition.x) && validSwipe)
            {
                Debug.Log("L_Swipe");
            }
          
        }

    }
}