unity—卡牌翻转效果(2)
上一篇的卡片翻转效果在应用中有一些问题,即当点击非卡牌区域,卡牌依旧会翻转。
这一篇的效果就是只有点击卡牌区域时才能翻转卡牌,与上一篇的制作方式不太相同。
将图片导入unity,这个图片是正面和反面在一起的,中间有一些透明像素,便于后面切割。
更改设置,如图2、3

设置完后,点击右侧的sprite editor按钮。
点击左上方slice(切割)-->slice,再点击左右两边的图片在4处重新命名,之后点击右上角Apply,再关闭窗口

在资源面板上,把图片的正面拖到左侧的面板上。

点击图片,给图片添加box collider,勾选is trigger

新建C#代码,内容如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class card : MonoBehaviour
{
private SpriteRenderer rend;
[SerializeField]
private Sprite faceSprite,backSprite;
private bool coroutineAllowed,facedUp;
// Start is called before the first frame update
void Start()
{
rend=GetComponent<SpriteRenderer>();
rend.sprite=faceSprite;
coroutineAllowed=true;
facedUp=true;
}
private void OnMouseDown(){
if(coroutineAllowed){
StartCoroutine(RotateCard());
}
}
private IEnumerator RotateCard(){
coroutineAllowed=false;
if(!facedUp){
for(float i=0f;i<=180f;i+=10f){
transform.rotation=Quaternion.Euler(0f,i,0f);
if(i==90f){
rend.sprite=faceSprite;
}
yield return new WaitForSeconds(0.01f);
}
}
else if (facedUp){
for (float i=180f;i>=0f;i-=10f){
transform.rotation=Quaternion.Euler(0f,i,0f);
if(i==90f){
rend.sprite=backSprite;
}
yield return new WaitForSeconds(0.01f);
}
}
coroutineAllowed=true;
facedUp=!facedUp;
}
// Update is called once per frame
void Update()
{
}
}
将代码保存,拖到左侧的物体上,再将正面和反面依次拖到右侧代码下的框框里。

完成。