Unity phone touch screen input

Time:2022-5-9

1. Get screen input

New scriptTouchInput, add to maincamera

public class TouchInput : MonoBehaviour
{
    public LayerMask touchInputMask;  // Declare the level, and the ray is only detected with the set level
    private Camera myCamera;          // Declaration camera

    private List touchList = new List();    // To save the currently pressed object, you need to add it dynamically with list
    private GameObject[] touchesOld; // Save the last pressed object without dynamic addition. Compare it with the currently pressed object to determine which objects canceled the click
    private RaycastHit hit;
    void Start()
    {
        myCamera = GetComponent();
    }
    void Update()
    {
        If (input. Touchcount > 0) // if there is touch screen input
        {
            //Initialize touchesold and save all keys pressed in the previous frame
            touchesOld = new GameObject[touchList.Count];
            touchList.CopyTo(touchesOld);
            touchList. Clear();  // Clear the list to get new input and save the currently pressed object

            Foreach (touch in input. Touches) // traverse all touch screen inputs
            {
                Ray ray = myCamera. ScreenPointToRay(touch.position);    // Emit rays from the touch screen

                if (Physics.Raycast(ray, out hit, touchInputMask))
                {
                    GameObject recipient = hit. transform. gameObject;    // Gets the object that the ray collides with
                    touchList. Add(recipient);     // Add the object to the current touch list

                    If (touch. Phase = = touchphase. Began) // judge the type of touch screen. If it is just touching the screen
                    {
                        //Send a delegate and call the method of object ontouchdown
                        recipient.SendMessage("OnTouchDown", hit.point, SendMessageOptions.DontRequireReceiver);
                    }
                    If (touch. Phase = = touchphase. Ended) // judge the type of touch screen. If the finger leaves the screen
                    {
                        //Send a delegate and call the ontouchup method of the object
                        recipient.SendMessage("OnTouchUp", hit.point, SendMessageOptions.DontRequireReceiver);
                    }
                    //If you press and hold the screen or slide on the screen
                    if (touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved)    
                    {
                        //Send a delegate and call the method of the object ontouchstay
                        recipient.SendMessage("OnTouchStay", hit.point, SendMessageOptions.DontRequireReceiver);
                    }
                    If (touch. Phase = = touchphase. Cancelled) // if the number of fingers exceeds the tracking line, or touch the screen with a plane such as a face
                    {
                        //Send a delegate and call the method of the object ontouchexit
                        recipient.SendMessage("OnTouchExit", hit.point, SendMessageOptions.DontRequireReceiver);
                    }
                }
            }
            Foreach (GameObject g in touchesold) // traverse the objects clicked in the previous frame
            {
                If (! Touchlist. Contains (g)) // if the list does not contain objects from the previous frame
                {
                    //Then the delegate calls the ontouchexit method of the object, and the object has been cancelled clicking
                    g.SendMessage("OnTouchExit", hit.point, SendMessageOptions.DontRequireReceiver);
                }
            }
        }
    }
}

New scriptButton

public class Button : MonoBehaviour
{
    public Color defaultColor; 	// Default color
    public Color selectedColor; 	// Color after clicking
    private Material mat;
    private void Start()
    {
        mat = gameObject.GetComponent().material;
    }
    private void OnTouchDown()
    {
        mat.color = selectedColor;
    }
    private void OnTouchUp()
    {
        mat.color = defaultColor;
    }
    private void OnTouchStay()
    {
        mat.color = selectedColor;
    }
    private void OnTouchExit()
    {
        mat.color = defaultColor;
    }
}

Add several cubes toButtonAdd to cube

Set the color of each cube
Running results of build to mobile phone

2. Drag effect

The slider here is not the slider in unityui

It is a slider assembled with basic objects

Quad and cube in 3D objects are used here


Then you can create a boxcollider on the slider to restrict the movement of the button

New scriptSlider

public class Slider : MonoBehaviour
{
    public Transform button;
    private Vector3 targetPos;
    private void Start()
    {
        targetPos = button.position;
    }
    private void Update()
    {
        button.position = Vector3.Lerp(button.position, targetPos, Time.deltaTime * 10f);
    }
    void OnTouchStay(Vector3 point)
    {
        targetPos = new Vector3(point.x, targetPos.y, targetPos.z);
    }
}

ThenButtonAdd to button

After running, you can drag the button

The next step is to display the data, add a sub object with 3dtext set as slider, and adjust it to the appropriate position and size

New scriptSlider, add to slider

public class Slider : MonoBehaviour
{
    public Transform knbo;
    public TextMesh textMesh;
    private Vector3 targetPos;

    private float sliderPercent;
    private float sliderLength;

    private void Start()
    {
        sliderLength = gameObject.GetComponent().size.x - 0.4f;
        targetPos = knbo.position;
    }
    private void Update()
    {
        knbo.position = Vector3.Lerp(knbo.position, targetPos, Time.deltaTime * 10f);
		//Calculate the scale of the slider
        sliderPercent = Mathf.Clamp01((knbo.localPosition.x + sliderLength / 2) / sliderLength);
													//Keep one decimal place
        textMesh.text = string.Format(sliderName + ": " + "{0:F1}", sliderPercent);	
    }
    public float GetSliderPercent()
    {
        return sliderPercent;
    }
    void OnTouchStay(Vector3 point)
    {
        targetPos = new Vector3(point.x, targetPos.y, targetPos.z);
    }
}