亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Unity 沿 X 軸移動播放器

Unity 沿 X 軸移動播放器

C#
慕少森 2021-10-24 17:15:39
我正在嘗試根據手指位置創建沿 x 軸的玩家移動。我需要發生的事情:不是多點觸控。我想要這樣一個玩家可以放下一根手指并抓住那個位置。然后檢查玩家是否在 x 軸上沿屏幕拖動手指,并根據他們從第一次觸摸時拖動手指的位置向左或向右移動玩家。因此,如果他們觸摸屏幕并向左拖動:按速度向左移動,如果更改為向右拖動,則按速度向右移動。任何幫助都是極好的。
查看完整描述

2 回答

?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

最簡單的方法是存儲第一個觸摸位置,然后將 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;

    }


}

警告:此解決方案僅適用于具有可用觸摸輸入的設備(因為使用 Input.touches)。


查看完整回答
反對 回復 2021-10-24
  • 2 回答
  • 0 關注
  • 179 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號