unity_物體跟隨鼠標移動


1.2DSprite 鼠標點擊屏幕並移動

//該腳本掛在Sprite上
using UnityEngine;
public class PlayerControl : MonoBehaviour
{
    
    /// <summary>
    /// 判斷玩家是否可以移動
    /// </summary>
    bool isMove;
    void Update()
    {
        //開啟左右移動
        if (Input.GetMouseButtonDown(0))
            isMove = true;
        if (Input.GetMouseButtonUp(0))
            isMove = false;

        if (isMove)
        {
            Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            //限制超出屏幕
            if (pos.x < -2)
                pos.x = -2;
            else if (pos.x > 2)
                pos.x = 2;
            transform.position = new Vector3(Mathf.Lerp(transform.position.x, pos.x, 1.5f * Time.deltaTime), 0, -9);
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM