
在本文中,将在Unity中开发一个入门的拖放图片到格子里的游戏,如果拖拽未匹配图像的则无法拖进去,只有匹配的才可以正确放置在格子里。
例子需要用到俩个脚本,拖拽和放置脚本,话不多说开始制作这个游戏吧!!
1.下面是需要用到的一段拖动脚本,在脚本中只是想添加一行来禁用光线投射目标,这使能够从图像下方获取信息,停止拖动后,可以重新启用它。
脚本如下:
private Image _image;
public void OnBeginDrag(PointerEventData eventData)
{
var tempcolor = _image.color;
tempcolor.a = 0.5f;
_image.color = tempcolor;
_image.raycastTarget = false;
}
public void OnDrag( PointerEventData eventData)
{
transform. position = eventData.position;
}
public void OnEndDrag(PointerEventData eventData)
{
var tempcolor = _image.color;
tempcolor.a = 1f;
_image.color = tempcolor;
_image.raycastTarget = true;
}
// Start is called before the first frame update
void Start()
{
_image = GetComponent<Image>();
}
2.然后需要创建一个放置脚本并将其附加到格子里的图像。
脚本如下:
public class DropScript : MonoBehaviour,IDropHandler
{
[SerializeField] private GameObject _startingPoint,_startingPoint1;
public void onDrop(PointerEventData eventData)
{
eventData.pointerDrag.transform.position = transform.position;
Debug.Log(eventData.pointerDrag);
if (eventData.pointerDrag.name=="StarImage")
{
eventData.pointerDrag.transform.position = _startingPoint.transform.position;
}
else if (eventData.pointerDrag.name == "LightningImage")
{
eventData.pointerDrag.transform.position = _startingPoint1.transform.position;
}
}
3.事件数据的好处是可以获取从中拖动的对象的名称,如果它是其他图像,则让该图像回到起始位置。
现在我们就可以测试一下该拖放式游戏了。
最终效果:

…
以上是关于在U3D中制作拖放游戏的全部内容,如果你有任何反馈,请随时在本页面下方留言。