unity 实现图片拖拽交换位置 并显示是否正确 若正确则有正确的音效 不正确则返回原位
时间: 2023-05-16 22:07:43 浏览: 95
可以使用Unity的Drag and Drop功能来实现图片拖拽交换位置。首先,需要在图片上添加一个Draggable组件,然后在代码中实现OnDrag和OnDrop方法来处理拖拽和放置操作。在OnDrop方法中,可以检查图片是否被正确放置,并根据结果播放相应的音效。
以下是示例代码:
```
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class Draggable : MonoBehaviour, IDragHandler, IEndDragHandler, IDropHandler
{
private Vector3 startPosition;
private Transform startParent;
private bool isCorrectPosition;
public AudioClip correctSound;
public AudioClip incorrectSound;
public void OnDrag(PointerEventData eventData)
{
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData)
{
if (!isCorrectPosition)
{
transform.position = startPosition;
transform.SetParent(startParent);
}
}
public void OnDrop(PointerEventData eventData)
{
if (eventData.pointerDrag != null && eventData.pointerDrag.GetComponent<Draggable>() != null)
{
Draggable otherDraggable = eventData.pointerDrag.GetComponent<Draggable>();
if (otherDraggable != null)
{
if (otherDraggable.isCorrectPosition && isCorrectPosition)
{
AudioSource.PlayClipAtPoint(correctSound, transform.position);
}
else
{
AudioSource.PlayClipAtPoint(incorrectSound, transform.position);
}
SwapPositions(otherDraggable);
}
}
}
private void SwapPositions(Draggable otherDraggable)
{
Vector3 tempPosition = transform.position;
Transform tempParent = transform.parent;
transform.position = otherDraggable.transform.position;
transform.SetParent(otherDraggable.transform.parent);
otherDraggable.transform.position = tempPosition;
otherDraggable.transform.SetParent(tempParent);
}
private void Start()
{
startPosition = transform.position;
startParent = transform.parent;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("CorrectPosition"))
{
isCorrectPosition = true;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("CorrectPosition"))
{
isCorrectPosition = false;
}
}
}
```
在这个例子中,我们使用了一个Trigger来检测图片是否被正确放置。如果图片进入了正确的位置,就将isCorrectPosition标记为true。在OnDrop方法中,我们检查两个图片的isCorrectPosition属性,如果都为true,则播放正确的音效并交换它们的位置。否则,播放错误的音效并将图片返回原位。
希望这个例子能帮助你实现图片拖拽交换位置的功能。
阅读全文