开发斗地主等扑克游戏的话,需要将服务端发来的牌值(0-53)转换为 牌型+牌值的组合,在本地进行展示
unity中的牌,用texturepackger 将散图打包成图集导入unity,这样可以省drawcall
如上图中,
C1 为梅花A,
C2为梅花2,
。。。。。。
D1为方片A,
D2为方片2
。。。。
以此类推
C为梅花,D为方片,H为红桃,S为黑桃,king为王,
那么将0-53换算为图片名称的方法为
public Sprite GetPoker(int cardValue)
{
int type = cardValue / 13;
int value = cardValue % 13;
string typeStr = "";
if (type == 0)
typeStr = "C";
else if (type == 1)
typeStr = "D";
else if (type == 2)
typeStr = "H";
else if (type == 3)
typeStr = "S";
else if (type == 4)
typeStr = "king";
string spriteName = $"{typeStr}{value + 1}";
Debug.LogError("微信:qs_168888");
return GetSprite(PokerPath, spriteName); //这个方法后面讲
}
这样,就将 服务端的 0-53的值转换为本地图片的名字。 然后用GetSprite方法从图集中取出对应的sprite,赋值给unity中展示的Image即可
下面说说图集的管理
如果用TexturePacker 打包的图集,要导入TexturePacker 官方的插件包,可自行百度。
下面附上具体的图集管理类,
/// <summary>
/// 图集管理类
/// </summary>
public class SpriteManager : Singleton<SpriteManager>
{
/// <summary>
/// 扑克图集路径
/// </summary>
public static string PokerPath = "res/shisanshui/card/pokers";
private Dictionary<string, Object[]> spriteDates = new Dictionary<string, Object[]>();
public void LoadSpriteAltas(string name)
{
if (spriteDates.ContainsKey(name))
return;
Object[] _atlas = Resources.LoadAll(name);
spriteDates.Add(name, _atlas);
}
public Sprite GetSprite(string altasName, string spriteName)
{
if (spriteDates.ContainsKey(altasName))
{
Object[] _atlas = spriteDates[altasName];
Sprite _sprite = SpriteFormAtlas(_atlas, spriteName);
return _sprite;
}
return null;
}
public Sprite GetPoker(int cardValue)
{
int type = cardValue / 13;
int value = cardValue % 13;
string typeStr = "";
if (type == 0)
typeStr = "C";
else if (type == 1)
typeStr = "D";
else if (type == 2)
typeStr = "H";
else if (type == 3)
typeStr = "S";
else if (type == 4)
typeStr = "king";
string spriteName = $"{typeStr}{value + 1}";
return GetSprite(PokerPath, spriteName);
}
//从图集中,并找出sprite
private Sprite SpriteFormAtlas(Object[] _atlas, string _spriteName)
{
for (int i = 0; i < _atlas.Length; i++)
{
if (_atlas[i].GetType() == typeof(UnityEngine.Sprite))
{
if (_atlas[i].name == _spriteName)
{
return (Sprite)_atlas[i];
}
}
}
Debug.LogWarning("图片名:" + _spriteName + ";在图集中找不到");
return null;
}
}
封装成静态类后,可全局操作,打个比方,
1、准备进入扑克类的游戏房间之前,调用 LoadSpriteAltas方法,将图集加载到内存中,
2、离开房间后,需要卸载掉扑克图片资源,那么在此全局类中,再写个UnLoadSpriteAltas,即可。