obsidian/笔记文件/2.笔记/2d图片跟随鼠标平面移动.md
2025-03-26 00:02:56 +08:00

702 B
Raw Blame History

#unity/日常积累

拿到img和canvas画布对应的游戏实体在update函数处理就好

    public class test : MonoBehaviour
    {
        public GameObject img;
        public GameObject canvas;
        private void Update()
        {
            //得到画布的尺寸
            Vector2 uisize = canvas.GetComponent<RectTransform>().sizeDelta;
            
            float X = Input.mousePosition.x - Screen.width / 2f;
            float Y = Input.mousePosition.y - Screen.height / 2f;
            
            Vector2 finalPos = new Vector2(X * (uisize.x / Screen.width), Y * (uisize.y / Screen.height));
            img.transform.localPosition = finalPos;
        }
    }