使用触摸位置沿Y轴移动玩家

时间:2015-09-05 13:50:52

标签: c# android unity3d-2dtools

当我点击屏幕轻触屏幕时,我试图移动播放器,但仅沿Y轴移动。我试过这个:

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);

                }
            }    
        }

但是球员消失而不是移动。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您需要将触摸位置从屏幕转换为世界。这很容易做到,我刚刚将这个快速脚本拼凑在一起,希望它有所帮助:

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;
    }
}

这也允许您也在编辑器中进行测试。

我希望这会有所帮助。