14年那会需要用Unity做一个棋牌游戏.当时要对牌进行选择(有这个需求),因为当时只是小小白,Flash那一套注册事件找了半天没有找到,最后稀里糊涂的用了射线检测(我去).基于此,我觉得有必要写这篇文章.
Ⅰ, UI设计
在一张Image上挂载ClickCard脚本(实现了Click,选中和不选中的状态)
①, ClickCard 参数
a, moveCure : 牌向上(选中动画),向下(取消选中动画)的曲线
b, offy : 选中后,牌向上移动的距离(像素)
c, durationMove : 牌向上或者向下移动的时间(秒)
Ⅱ, ClickCard.cs代码
值得注意的是继承 UnityEngine.EventSystems.IPointerClickHandler
登录后复制
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class ClickCard : MonoBehaviour, IPointerClickHandler
{
/// <summary>
/// 移动曲线
/// </summary>
[SerializeField]
private AnimationCurve moveCurve;
/// <summary>
/// 选中后向上移动的距离(px)
/// </summary>
[SerializeField]
private float offY;
[SerializeField]
private float durationMove;
/// <summary>
/// 卡牌的当前状态
/// </summary>
private TypeCard status;
private Vector3 original;
private float accumulationX;
private Vector3 startVec;//开始位置
private Vector3 endVec;//结束位置
private float curDurationMove;
public void OnPointerClick(PointerEventData eventData)
{
if (eventData.clickCount == 1)
{
this.startVec = (this.transform as RectTransform).anchoredPosition;
status = status == TypeCard.UN_SELECTED ? TypeCard.SELECTED : TypeCard.UN_SELECTED;
switch (status)
{
case TypeCard.UN_SELECTED:
this.endVec = this.original;
break;
case TypeCard.SELECTED:
this.endVec = this.original;
this.endVec.y += this.offY;
break;
}
//根据距离(px)减少时间
float curOffY = Mathf.Abs(this.startVec.y - this.endVec.y);
if (curOffY == 0)
{
this.accumulationX = 1;
}
else
{
this.accumulationX = 0;
this.curDurationMove = Mathf.Abs(curOffY / this.offY) * this.durationMove;
}
}
}
void Awake()
{
this.status = TypeCard.UN_SELECTED;
this.accumulationX = 1;
}
// Start is called before the first frame update
void Start()
{
this.original = (this.transform as RectTransform).anchoredPosition;
}
// Update is called once per frame
void Update()
{
if (this.accumulationX == 1) return;
this.accumulationX += Time.deltaTime / this.curDurationMove;
if (this.accumulationX > 1)
this.accumulationX = 1;
(this.transform as RectTransform).anchoredPosition = Vector3.Lerp(startVec, endVec, this.moveCurve.Evaluate(this.accumulationX));
}
}
enum TypeCard : ushort
{
UN_SELECTED = 0,
SELECTED = 1,
}
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删