拖动对象时会跳到中心
Posted
技术标签:
【中文标题】拖动对象时会跳到中心【英文标题】:Object jumps to the center when dragging it 【发布时间】:2018-10-29 19:11:37 【问题描述】:您如何使用IBeginDragHandler
并设置拖动位置以保持一致而不是突然切换到游戏对象的中心?
这是我的简单代码,用于抓取和反对并将它们释放到新位置。但是,我意识到通过角落抓取对象(2D)会自动将指针设置为中心。像这样离开拖累感觉很糟糕。
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
public void OnBeginDrag(PointerEventData eventData)
Debug.Log ("Started dragging");
public void OnDrag(PointerEventData eventData)
Debug.Log ("Currently dragging");
this.transform.position = eventData.position;
public void OnEndDrag(PointerEventData eventData)
Debug.Log ("Ended dragging");
【问题讨论】:
【参考方案1】:您需要使用偏移量。调用OnPointerDown
时获取偏移量。在调用 OnDrag
时应用此偏移量。
对于 2D 精灵:
Camera mainCamera;
float zAxis = 0;
Vector3 clickOffset = Vector3.zero;
// Use this for initialization
void Start()
zAxis = transform.position.z;
public void OnPointerDown(PointerEventData eventData)
clickOffset = transform.position - mainCamera.ScreenToWorldPoint(new Vector3(eventData.position.x, eventData.position.y, zAxis));
public void OnDrag(PointerEventData eventData)
//Use Offset To Prevent Sprite from Jumping to where the finger is
Vector3 tempVec = mainCamera.ScreenToWorldPoint(eventData.position) + clickOffset;
tempVec.z = zAxis; //Make sure that the z zxis never change
transform.position = tempVec;
public void OnEndDrag(PointerEventData eventData)
对于 UI 对象,偏移量仍然是相同的解决方案,但也应使用 ScreenPointToLocalPointInRectangle
。
public class Draggable : MonoBehaviour, IDragHandler, IBeginDragHandler
public Canvas parentCanvas;
Vector3 Offset = Vector3.zero;
public void OnPointerDown(PointerEventData eventData)
Vector2 pos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(parentCanvas.transform as RectTransform, eventData.position, parentCanvas.worldCamera, out pos);
Offset = transform.position - parentCanvas.transform.TransformPoint(pos);
public void OnDrag(PointerEventData eventData)
Vector2 movePos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(parentCanvas.transform as RectTransform, eventData.position, parentCanvas.worldCamera, out movePos);
transform.position = parentCanvas.transform.TransformPoint(movePos) + Offset;
【讨论】:
以上是关于拖动对象时会跳到中心的主要内容,如果未能解决你的问题,请参考以下文章
SpringCloud集成Security安全(Eureka注册中心)