前言
本节主要实现卡片栏和植物的拖拽放置
卡片栏
绘制简单的卡牌UI,我们用一个黑色的图片覆盖作为卡牌进度
新增Card脚本,控制卡牌进度和黑图显示
public class Card : MonoBehaviour { private GameObject darkBg;//黑图 private GameObject progressBar;//进度 public float waitTime; //等待时间 public int useSun;//需要阳光 void Start() { darkBg = transform.Find("黑色底图").gameObject; progressBar = transform.Find("黑色进度").gameObject; } void Update() { UpdateProgress(); UpdateDarkBg(); } void UpdateProgress(){ progressBar.GetComponent<Image>().fillAmount -= 1 / waitTime * Time.deltaTime; } void UpdateDarkBg(){ if(progressBar.GetComponent<Image>().fillAmount == 0){ darkBg.SetActive(false); }else{ darkBg.SetActive(true); } } }
配置
效果
配置触发器格子
为了节省时间,可以用Grid Layout Group组件,进行排序,效果如下
卡牌拖拽
对拖拽不太懂的小伙伴可以查看我之前的文章:【unity】几种常用的拖拽方法(内置方法 + 接口 + Event Trigger组件)
修改Card
public class Card : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler { public GameObject prefab;//预制体 public LayerMask layerMask;//检测图层 private GameObject thisObject; //。。。 //开始拖拽 public void OnBeginDrag(PointerEventData eventData) { Debug.Log("开始拖拽"); if (progressBar.GetComponent<Image>().fillAmount != 0) return; thisObject = Instantiate(prefab, transform.position, Quaternion.identity); } //拖拽中 public void OnDrag(PointerEventData eventData) { Debug.Log("拖拽中"); if (thisObject == null) return; //植物跟随鼠标 Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); thisObject.transform.position = new Vector2(mousePosition.x, mousePosition.y); // 将物体位置设置为鼠标位置 } //拖拽结束 public void OnEndDrag(PointerEventData eventData) { Debug.Log("拖拽结束"); if (thisObject == null) return; Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); Vector2 mousePosition2D = new Vector2(mousePosition.x, mousePosition.y); RaycastHit2D hit = Physics2D.Raycast(mousePosition2D, Vector2.zero, Mathf.Infinity, layerMask);//鼠标“点检测”射线 if (hit.collider != null && hit.collider.transform.childCount == 0) { thisObject.transform.parent = hit.transform; thisObject.transform.localPosition = Vector2.one; thisObject = null; //重置进度 progressBar.GetComponent<Image>().fillAmount = 1; //TODO扣除阳光 } else { Destroy(thisObject); } } }
而配置对应的预制体
源码
源码不出意外的话我会放在最后一节