15. 创建卡牌布局

在项目中添加 CardLayoutManager

代码如下

using System.Collections.Generic;
using UnityEngine;

public class CardLayoutManager : MonoBehaviour
{
    public bool isHorizontal;
    // 摄像机的大小是6,分辨率是1920x1080,也就是说摄像机可以看到(-10.7,-6)~(10.7,6)的物体,这里让手牌的位置从-3.5~3.5
    public float maxWidth = 7f;
    // 卡牌与卡牌之间最大的间隔是2
    public float cardSpacing = 2f;
    // 中心点位置,表示卡牌在屏幕中的位置
    public Vector3 centerPoint;

    [SerializeField]
    private List<Vector3> cardPositions = new List<Vector3>();
    private List<Quaternion> cardRotations = new List<Quaternion>();

    /// <summary>
    /// 当一共有 totalCards 张卡牌的时候,计算出第 index 张卡牌的坐标和旋转
    /// </summary>
    /// <param name="index"></param>
    /// <param name="totalCards"></param>
    /// <returns></returns>
    public CardTransform GetCardTransform(int index, int totalCards)
    {
        CalculatePositoin(totalCards, isHorizontal);

        return new CardTransform(cardPositions[index], cardRotations[index]);
    }

    /// <summary>
    /// 计算卡牌的位置
    /// </summary>
    /// <param name="numberOfCards">当前有多少张卡牌</param>
    /// <param name="horizontal">横向还是扇形</param>
    private void CalculatePositoin(int numberOfCards, bool horizontal)
    {
        // 首先要清理一下之前算好的位置
        cardPositions.Clear();
        cardRotations.Clear();

        if (horizontal)
        {
            // 卡牌是横向排列的

            // 一共有 numberOfCards 张卡牌,卡牌与卡牌之间的间距是 cardSpacing,那么它们之间的总间距是 currentWidth
            float currentWidth = cardSpacing * (numberOfCards - 1);
            // 如果卡牌太多超过 maxWidth 的话,就需要将最大宽度设置为 maxWidth
            float totalWidth = Mathf.Min(currentWidth, maxWidth);

            // 算出当前卡牌与卡牌之间的间距
            float currentSpacing = totalWidth > 0 ? totalWidth / (numberOfCards - 1) : 0;
            for (int i = 0; i < numberOfCards; i++) 
            {
                // 让卡牌从最左边以此排过来
                float xPos = 0 - totalWidth / 2 + currentSpacing * i;

                var pos = new Vector3(xPos, centerPoint.y, 0);
                var rotation = Quaternion.identity;

                // 然后记录它们的位置和旋转
                cardPositions.Add(pos);
                cardRotations.Add(rotation);
            }
        }
    }
}

其中使用CardTransform来存储卡牌的位置和旋转

抽卡并调整位置

从牌堆中抽取一张卡牌之后,需要调整它们的位置

最终效果

抽一张牌之后变成

项目相关代码

代码仓库:https://gitee.com/nbda1121440/DreamOfTheKingdom.git

标签:20240305_1211

posted @ 2024-03-05 12:33  hellozjf  阅读(61)  评论(0编辑  收藏  举报