代码之家  ›  专栏  ›  技术社区  ›  JGrn84

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

  •  0
  • JGrn84  · 技术社区  · 9 年前

    当屏幕被点击到屏幕被点击的位置时,我试图移动一个播放器,但只能沿着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 回复  |  直到 9 年前
        1
  •  1
  •   Motonstron    9 年前

    您需要将触摸位置从“屏幕”转换为“世界”。这很容易做到,我刚刚完成了这个快速脚本,希望它有帮助:

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

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

    我希望这有帮助。