Search code examples
c#androidunity3d-2dtools

Move a player along Y axis using touch location


I'm trying to move a player when the screen is tapped to where the screen is tapped, but only along the Y axis. I've tried this:

Vector2 touchPosition;
        [SerializeField] float speed = 1f;   

void Update() {

            for (var i = 0; i < Input.touchCount; i++) {

                if (Input.GetTouch(i).phase == TouchPhase.Began) {

                    // assign new position to where finger was pressed
                    transform.position = new Vector3 (transform.position.x, Input.GetTouch(i).position.y, transform.position.z);

                }
            }    
        }

But the player disappears rather than moves. What am I doing wrong?


Solution

  • You need to convert the touch position from Screen to World. This is very easy to do, I've just knocked this quick script together, hopefully it helps:

    using UnityEngine;
    using System.Collections;
    
    public class TouchSomething : MonoBehaviour 
    {
        public GameObject thingToMove;
    
        public float smooth = 2;
    
        private Vector3 _endPosition;
    
        private Vector3 _startPosition;
    
        private void Awake()
        {
            _startPosition = thingToMove.transform.position;
        }
    
        private void Update()
        {
            if(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
            {
                _endPosition = HandleTouchInput();
            }
            else
            {
                _endPosition = HandleMouseInput();
            }
    
            thingToMove.transform.position = Vector3.Lerp(thingToMove.transform.position, new Vector3(_endPosition.x, _endPosition.y, 0), Time.deltaTime * smooth);
        }
    
        private Vector3 HandleTouchInput()
        {
            for (var i = 0; i < Input.touchCount; i++) 
            {
                if (Input.GetTouch(i).phase == TouchPhase.Began) 
                {
                    var screenPosition = Input.GetTouch(i).position;
                    _startPosition = Camera.main.ScreenToWorldPoint(screenPosition);
                }
            }
    
            return _startPosition;
        }
    
        private Vector3 HandleMouseInput()
        {
            if(Input.GetMouseButtonDown(0))
            {
                var screenPosition = Input.mousePosition;
                _startPosition = Camera.main.ScreenToWorldPoint(screenPosition);
            }
    
            return _startPosition;
        }
    }
    

    This allows you to also test in the editor as well.

    I hope this helps.