首页 文章

Unity沿X轴移动播放器

提问于
浏览
3

我正在尝试根据手指位置创建沿x轴的玩家移动 .

What I need to Happen: 不是多点触控 . 我想要它,所以玩家可以放下一根手指并 grab 那个位置 . 然后检查玩家是否在x轴上沿着屏幕拖动手指并根据他们从第一次触摸拖动手指的位置向左或向右移动玩家 .

因此,如果他们触摸屏幕并向左拖动:向左移动速度,如果它改变为向右拖动,则向右移动 .

任何帮助都是极好的 .

2 回答

  • 2

    最简单的方法是存储第一个触摸位置,然后将X与该位置进行比较:

    public class PlayerMover : MonoBehaviour
    {
        /// Movement speed units per second
        [SerializeField]
        private float speed;
    
        /// X coordinate of the initial press
        // The '?' makes the float nullable
        private float? pressX;
    
    
    
        /// Called once every frame
        private void Update()
        {
            // If pressed with one finger
            if(Input.GetMouseButtonDown(0))
                pressX = Input.touches[0].position.x;
            else if (Input.GetMouseButtonUp(0))
                pressX = null;
    
    
            if(pressX != null)
            {
                float currentX = Input.touches[0].position.x;
    
                // The finger of initial press is now left of the press position
                if(currentX < pressX)
                    Move(-speed);
    
                // The finger of initial press is now right of the press position
                else if(currentX > pressX)
                    Move(speed);
    
                // else is not required as if you manage (somehow)
                // move you finger back to initial X coordinate
                // you should just be staying still
            }
        }
    
    
        `
        /// Moves the player
        private void Move(float velocity)
        {
            transform.position += Vector3.right * velocity * Time.deltaTime;
        }
    
    }
    

    WARNING: 此解决方案仅适用于具有触摸输入的设备(因为使用了Input.touches) .

  • 6

    使用此答案中提供的代码@programmer:Detect swipe gesture direction

    您可以轻松检测您正在滑动/拖动的方向 . 替换调试

    void OnSwipeLeft()
    {
        Debug.Log("Swipe Left");
    }
    
    void OnSwipeRight()
    {
        Debug.Log("Swipe Right");
    }
    

    使用可以移动角色的功能 . 如果您使用RigidBody移动角色,您可以使用https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html . 如果它是普通对象,你可以通过调整 transform.position 来移动它 .

    如果您需要有关如何移动刚体\普通对象的更多信息,请告诉我您的游戏类型以及有关如何设置播放器的更多详细信息 .

相关问题