unity 鼠标拖拽两个图片交换位置
时间: 2023-05-17 12:04:51 浏览: 240
可以通过以下代码实现:
```csharp
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class ImageSwap : MonoBehaviour, IDragHandler, IEndDragHandler
{
public Image image1;
public Image image2;
private Vector2 image1Position;
private Vector2 image2Position;
public void OnDrag(PointerEventData eventData)
{
if (eventData.pointerCurrentRaycast.gameObject == image1.gameObject)
{
image1.transform.position = eventData.position;
}
else if (eventData.pointerCurrentRaycast.gameObject == image2.gameObject)
{
image2.transform.position = eventData.position;
}
}
public void OnEndDrag(PointerEventData eventData)
{
if (eventData.pointerCurrentRaycast.gameObject == image1.gameObject)
{
image2Position = image2.transform.position;
image2.transform.position = image1Position;
image1.transform.position = image2Position;
}
else if (eventData.pointerCurrentRaycast.gameObject == image2.gameObject)
{
image1Position = image1.transform.position;
image1.transform.position = image2Position;
image2.transform.position = image1Position;
}
}
}
```
这段代码实现了鼠标拖拽两个图片交换位置的功能。在场景中添加两个 Image 组件,分别命名为 image1 和 image2,并将 ImageSwap 脚本挂载到一个空物体上。在脚本中将 image1 和 image2 分别赋值为场景中的两个 Image 组件,然后在 OnDrag 和 OnEndDrag 方法中实现图片的拖拽和位置交换。
阅读全文