0
我有一個畫布設置,它在屏幕空間 - 疊加和我幾乎有我在找什麼,但結果只是一點點關閉。通過一點點關閉,我的意思是當我點擊並按住拖動我的廣告資源時,它不是鼠標所在的位置,但它非常接近。現在拖動不起作用,但當我完成拖動我的GameObject正確地返回到它的相應位置。在Unity中的疊加畫布中點擊並拖動一個遊戲對象
我的代碼:
void Awake(){
rectTrans = GetComponent<RectTransform>();
}
void Start(){
localRectTrans = rectTrans.localPosition;
}
public void OnPointerUp(PointerEventData data){
// IF we are dragging an item
if(itemBeingDragged != null){
itemBeingDragged = null;
// return this gameobject to its original location.
rectTrans.localPosition = localRectTrans;
}
}
public void OnBeginDrag(PointerEventData data){
// IF we have an item to drag.
if(isItem){
// Set the itemBeingDragged to this gameobject.
itemBeingDragged = gameObject;
// Get the starting mouse location for dragging.
startMousePos = Input.mousePosition;
}
}
public void OnDrag(PointerEventData data){
// IF we have an item to drag in this inventory slot.
if(isItem){
// Get the location of the mouse.
Vector2 curMousePosition = Input.mousePosition;
// Get the difference in position from when the mouse was first clicked to where it is currently being dragged.
Vector2 diffInPos = curMousePosition - startMousePos;
// The current position based on the difference in position with the mouse and the local position of this inventory slot.
Vector2 curPos = localRectTrans + diffInPos;
transform.localPosition = curPos;
}
}
我怎樣才能得到這實際上正是我的鼠標光標?我覺得我很親密,但只是不斷畫空白。
嘿程序員,我很欣賞的幫助,但我仍然得到的呃ROR。上面的代碼我使用,我有一個GIF在這裏看看:http://imgur.com/ED6YKU8。我想我需要澄清更多,並說rectTrans是我的庫存插槽,這是我目前的版本:http://clip2net.com/s/3y4J6bo。我還嘗試在鏈接的代碼中使用第一個參數作爲我的畫布的RectTransform,這就是它在GIF中的樣子:http://imgur.com/2EeoTlf。如果您需要更多信息,請與我們聯繫。 – JoeyL
@JoeyL你留下了一些信息,所以我做了一些猜測工作。請將** Inventory Slot 1 **的矩形變換對齊至左下角,如http://i.imgur.com/2AGytrc.png。測試它。如果不起作用,請撤消它,然後將** Inventory Bag **的矩形變換對齊到左下角。如果它不起作用,請再次撤消它,然後將** Inventory **的矩形變換對齊到左下角。如果失敗,請回報。我有另一種解決方案。 – Programmer
@JoeyL如果我上面說的失敗,請嘗試'yourInventory.localPosition = pos;'而不是'rectTrans.anchoredPosition = pos;'pos是我的答案中代碼的位置。讓我知道這些工作是否適合你。 – Programmer