Ⅰ, 将屏幕坐标转换成相对坐标. 猜测至少有2个重要参数: ①, 相对于哪个GO的相对坐标 . ②, 屏幕坐标canvas
Ⅱ, Scene布置ide
Ⅲ, 脚本this
using UnityEngine; using UnityEngine.UI; public class UIScripts : MonoBehaviour { [SerializeField] private Image image; public Canvas canvas; void Start() { Vector2 pos; if (RectTransformUtility.ScreenPointToLocalPointInRectangle( canvas.transform as RectTransform, this.image.transform.position, this.canvas.worldCamera, out pos)) { Debug.Log(pos); } this.getImagePos(); } private void getImagePos() { RectTransform rectT = this.image.transform as RectTransform; Debug.Log(" ------ " + rectT.anchoredPosition); } void Update() { } }
解析代码参数spa
参数1,(canvas.transform as RectTransform): 获得相对于参数1(GO)上坐标code
参数2( 注意: canvas 的render mode为: Screen Space -Overlay , 因此Image的世界坐标就是屏幕坐标): 获得Image屏幕坐标在参数1上的相对位置orm
结果以下:blog
Ⅰ, 将Image移动到鼠标点击的位置ip
Ⅱ, 脚本以下get
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UIClickScripts : MonoBehaviour { [SerializeField] private Image image; public Canvas canvas; private Vector2 pos; void Start() { } void Update() { if (Input.GetMouseButton(0)) { if (RectTransformUtility.ScreenPointToLocalPointInRectangle( this.canvas.transform as RectTransform,//Local Panel Input.mousePosition,//Screen Pos canvas.worldCamera, out this.pos )) { (this.image.transform as RectTransform).anchoredPosition = this.pos; } } } }
Ⅲ, 其实能够作一个缓动用Tween 或者用Unity自动的Lerp都行it