1、cs传递消息用的基本Model
public class SocketModel
{
public int type{get;set;}
public int area{get;set;}
public int command{get;set;}
public string message{get;set;}
}
public class CreateButtonModel
{
public int index{get;set;}
public PlayerModel player{get;set;}
}
public class PlayerModel
{
public string id{get;set;}
public string name{get;set;}
public int job{get;set;}
public int level{get;set;}
public int exp{get;set;}
public int atk{get;set;}
public int def{get;set;}
public int hp{get;set;}
public int maxHp{get;set;}
public Vector3 point{get;set;}
public Vector4 rotation{get;set;}
public int map{get;set;}
public PlayerModel(){
}
public PlayerModel(PlayerModel model){
this.job=model.job;
this.level=model.level;
this.exp=model.exp;
this.atk=model.atk;
this.def=model.def;
this.hp=model.hp;
this.maxHp=model.maxHp;
}
public PlayerModel(int job,int level,int exp,int atk,int def,int map,int hp,int maxHp){
this.job=job;
this.level=level;
this.exp=exp;
this.atk=atk;
this.def=def;
this.hp=hp;
this.maxHp=maxHp;
}
}
2、游戏状态
public class GameState
{
public const int RUN=0;
public const int WINDOW=1;
public const int ACC_REG=2;
public const int LOADING=3;
public const int PLAYER_CREATE=4;
public const int WAIT=5;
}
主角状态
public class PlayerStateConstans
{
public const int FORWARD=0;
public const int BACK=1;
public const int LEFT=2;
public const int RIGHT=3;
public const int IDLE=4;
public const int ATTACK=5;
public const int SKILL=6;
public const int DIE=7;
}
3、全局变量
public class GameInfo
{
public static int GAME_STATE=0;
public static string ACC_ID="";
public static float LOAD_PRORESS=0f;
public static int LAST_STATE=0;
public static PlayerModel selectModel;
public static PlayerModel myModel;
public static int PLAYER_STATE=PlayerStateConstans.IDLE;
}
4.解决Json的问题
class Coding<T>
{
public static string encode(T model){
return JsonMapper.ToJson(model);
}
public static T decode(string message){
return JsonMapper.ToObject<T>(message);
}
}
public class StringDTO
{
public string value;
public StringDTO ()
{
}
public StringDTO(string v){
this.value = v;
}
}
public class BoolDTO
{
public bool value;
public BoolDTO (){
}
public BoolDTO(bool v){
this.value = v;
}
}
public class IntDTO
{
public int value;
public IntDTO ()
{
}
public IntDTO(int v){
this.value = v;
}
}
public class Vector3
{
public double X {get; set;}
public double Y {get; set;}
public double Z {get; set;}
public Vector3(){}
public Vector3(UnityEngine.Vector3 v){
X = v.x;
Y = v.y;
Z = v.z;
}
}
public class Vector4
{
public double X {get; set;}
public double Y {get; set;}
public double Z {get; set;}
public double W {get; set;}
public Vector4(){}
public Vector4(UnityEngine.Quaternion v){
X = v.x;
Y = v.y;
Z = v.z;
W = v.w;
}
}
发送消息用到的
public class LoginDTO
{
public string userName;
public string passWord;
}
public class MoveDTO
{
public string Id{get; set;}
public int Dir{get;set;}
public Assets.Model.Vector4 Rotation{get;set;}
public Assets.Model.Vector3 Point{get;set;}
}
public class CreateDTO{
public int job{get;set;}
public string name{get;set;}
}
public class EnterMapDTO
{
public int map;
public Assets.Model.Vector3 point {get; set;}
public Assets.Model.Vector4 rotation {get; set;}
}
public class AttackDTO
{
public int attType { get; set; }
public Assets.Model.Vector3 point { get; set; }
public Assets.Model.Vector4 Rotation { get; set; }
public string targetId { get; set; }
public string userId { get; set; }
}
public class BeAtkDTO{
public string id { get; set; }
public int value { get; set; }
}
5.用到的Protocol
public class Protocol
{
public const int LOGIN = 0;
public const int MAP = 1;
public const int USER = 2;
}
public class LoginProtocol
{
public const int LOGIN_CREQ = 0;
public const int LOGIN_SRES = 1;
public const int REG_CREQ = 2;
public const int REG_SRES = 3;
}
public class UserProtocol
{
public const int LIST_CREQ = 0;
public const int LIST_SRES = 1;
public const int CREATE_CREQ = 2;
public const int CREATE_SRES = 3;
public const int SELECT_CREQ = 4;
public const int SELECT_SRES = 5;
public const int REMOVE_CREQ = 6;
public const int REMOVE_SRES = 7;
}
public class MapProtocol
{
public const int ENTER_CREQ = 0;
public const int ENTER_SRES = 1;
public const int ENTER_BRO = 2;
public const int MOVE_CREQ = 3;
public const int MOVE_BRO = 4;
public const int LEAVE_CREQ = 5;
public const int LEAVE_BRO = 6;
public const int TALK_CREQ = 7;
public const int TALK_BRO = 8;
public const int ATTACK_CREQ = 9;
public const int ATTACK_BRO = 10;
public const int MONSTER_INIT_SRES = 11;
public const int BE_ATTACK_CREQ = 12;
public const int BE_ATTACE_BRO = 13;
public const int MONSTER_DIE_BRO = 14;
public const int EXP_UP_SRES = 15;
public const int LEVEL_UP_BRO = 16;
public const int MONSTER_RELIVE_BRO = 17;
//public const int SKILL_CREQ = 18;
//public const int SKILL_BRO = 19;
}
6、警告信息
public class WindowConstans{
public static List<int> windowList=new List<int>();
public const int INPUT_ERROR=0;
public const int STATE_ERROR=1;
public const int SOCKET_TYPE_ERROR=2;
public const int ACC_REG_SUCCEED=3;
public const int ACC_REG_FAIL=4;
public const int LOGIN_FAIL=5;
public const int JOB_CREATE_ERROR=6;
public const int JOB_CREATE_SUCCEED=7;
}
7、存储loading状态下的数据
public class LoadData
{
public static List<PlayerModel> loadingPlayerList = new List<PlayerModel>();
}
8、客户端发送消息及处理服务器反馈回来的消息
public class NetWorkScript
{
private static NetWorkScript script;
private Socket socket;
public static string host ="127.0.0.1";//服务器IP地址
private int port = 10100;//服务器端口
private byte[] readM = new byte[1024];
private ByteArray ioBuff=new ByteArray();
private int dataSize;
private List<SocketModel> messages = new List<SocketModel>();
private bool isRead = false;
//获取连接对象
public static NetWorkScript getInstance() {
if (script == null) {
//第一次调用的时候 创建单例对象 并进行初始化操作
script = new NetWorkScript();
script.init();
}
return script;
}
private void init() {
try
{
//创建socket连接对象
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接到服务器
socket.Connect(host, port);
//连接后开始从服务器读取网络消息
socket.BeginReceive(readM, 0, 1024, SocketFlags.None, ReceiveCallBack,readM);
Debug.Log("socket session open");
}
catch (Exception e) {
//连接失败 打印异常
Debug.Log("Connect error:"+e.Message);
}
}
public void sendMessage(int type, int area, int command, string message) {
ByteArray arr= new ByteArray();
arr.WriteInt(type);
arr.WriteInt(area);
arr.WriteInt(command);
if (message != null)
{
arr.WriteInt(message.Length);
arr.WriteUTFBytes(message);
// arr.WriteUTFBytes(message);
}
else {
arr.WriteInt(0);
}
try
{
socket.Send(arr.Buffer);
}
catch {
Debug.Log("socket error");
}
}
public void onData()
{
//消息读取完成后开始解析
if(ioBuff.Length<4){
//包头为长度4的整型
isRead = false;
return;
}
dataSize=ioBuff.ReadInt();
Debug.Log("dataSize"+dataSize);
if(dataSize>ioBuff.Length-4){
//包长不够 等下个包的到来
Debug.Log("包长不够");
ioBuff.Postion=0;
isRead = false;
return;
}
ByteArray ioData=new ByteArray();
ioData.WriteBytes(ioBuff.Buffer,4,dataSize);
ioBuff.Postion+=dataSize;
int type = ioData.ReadInt();//表示消息类型 我们这里有两种
int area = ioData.ReadInt();//这里表示消息的区域码 在登录这样的服务器单例模块中 没有效果 在地图消息的时候用于区分属于哪张地图来的消息
int command = ioData.ReadInt();//模块内部协议---具体稍后描述
int len = ioData.ReadInt();
string m=null;
if (len > 0) { m = ioData.ReadUTFBytes((uint)len); }//这里开始就是读取服务器传过来的消息对象了 是一串json字符串
//转换为Socket消息模型
SocketModel model= new SocketModel();
model.type = type;
model.area = area;
model.command = command;
model.message = m;
Debug.Log(type+" "+area+" "+command+"length"+(16+len));
//消息接收完毕后,存入收到消息队列
messages.Add(model);
ByteArray bytes=new ByteArray();
bytes.WriteBytes(ioBuff.Buffer, ioBuff.Postion, ioBuff.Buffer.Length - ioBuff.Postion);
ioBuff=bytes;
onData();
//Debug.Log("插入队列后"+arr.Buffer[12+len+1]);
}
//这是读取服务器消息的回调--当有消息过来的时候BgenReceive方法会回调此函数
private void ReceiveCallBack(IAsyncResult ar)
{
int readCount = 0;
try
{
//读取消息长度
readCount = socket.EndReceive(ar);//调用这个函数来结束本次接收并返回接收到的数据长度。
Debug.Log("读取消息长度" + readCount);
byte[] bytes = new byte[readCount];//创建长度对等的bytearray用于接收
Buffer.BlockCopy(readM, 0, bytes, 0, readCount);//拷贝读取的消息到 消息接收数组
ioBuff.WriteBytes(bytes);
Debug.Log(ioBuff.Buffer.Length);
if (!isRead){
isRead = true;
onData();//消息读取完成
}
}
catch (SocketException)//出现Socket异常就关闭连接
{
socket.Close();//这个函数用来关闭客户端连接
return;
}
socket.BeginReceive(readM, 0, 1024, SocketFlags.None, ReceiveCallBack,readM);
}
public List<SocketModel> getList() {
return messages;
}
}
此类主要用于项目中的消息体与二进制之间的转换使用时需注意,写入与读取类型顺序需保持一次,否则读取失败
public class ByteArray
{
private MemoryStream m_Stream = new MemoryStream();
private BinaryReader m_Reader = null;
private BinaryWriter m_Writer = null;
public ByteArray()
{
Init();
}
public ByteArray(MemoryStream ms)
{
m_Stream = ms;
Init();
}
public ByteArray(byte[] buffer)
{
m_Stream = new MemoryStream(buffer);
Init();
}
private void Init()
{
m_Writer = new BinaryWriter(m_Stream);
m_Reader = new BinaryReader(m_Stream);
}
public int Length
{
get { return (int)m_Stream.Length; }
}
public int Postion
{
get { return (int)m_Stream.Position; }
set { m_Stream.Position = value; }
}
public byte[] Buffer
{
get { return m_Stream.GetBuffer(); }
}
internal MemoryStream MemoryStream { get { return m_Stream; } }
//读取boolean
public bool ReadBoolean()
{
return m_Reader.ReadBoolean();
}
//读取byte
public byte ReadByte()
{
return m_Reader.ReadByte();
}
//读取byte[]
public void ReadBytes(byte[] bytes, uint offset, uint length)
{
byte[] tmp = m_Reader.ReadBytes((int)length);
for (int i = 0; i < tmp.Length; i++)
bytes[i + offset] = tmp[i];
}
[/i]//读取double[i]
public double ReadDouble()
{
return m_Reader.ReadDouble();
}
[/i]//读取float[i]
public float ReadFloat()
{
byte[] bytes = m_Reader.ReadBytes(4);
byte[] invertedBytes = new byte[4];
for (int i = 3, j = 0; i >= 0; i--, j++)
{
invertedBytes[j] = bytes[i];
}
float value = BitConverter.ToSingle(invertedBytes, 0);
return value;
}
[/i][/i]//读取int[i][i]
public int ReadInt()
{
return m_Reader.ReadInt32();
}
[/i][/i]//读取短整型[i][i]
public short ReadShort()
{
return m_Reader.ReadInt16();
}
[/i][/i]//读取正byte[i][i]
public byte ReadUnsignedByte()
{
return m_Reader.ReadByte();
}
[/i][/i]//读取正整型[i][i]
public uint ReadUnsignedInt()
{
return (uint)m_Reader.ReadInt32();
}
[/i][/i]//读取正短整型[i][i]
public ushort ReadUnsignedShort()
{
return m_Reader.ReadUInt16();
}
[/i][/i]//读取utf字符串到bytearray结尾[i][i]
public string ReadUTF()
{
return m_Reader.ReadString();
}
[/i][/i]//读取指定长度的字符串[i][i]
public string ReadUTFBytes(uint length)
{
if (length == 0)
return string.Empty;
UTF8Encoding utf8 = new UTF8Encoding(false, true);
byte[] encodedBytes = m_Reader.ReadBytes((int)length);
string decodedString = utf8.GetString(encodedBytes, 0, encodedBytes.Length);
return decodedString;
}
[/i][/i]//写入boolean[i][i]
public void WriteBoolean(bool value)
{
m_Writer.BaseStream.WriteByte(value ? ((byte)1) : ((byte)0));
}[/i][/i]//写入byte[i][i]
public void WriteByte(byte value)
{
m_Writer.BaseStream.WriteByte(value);
}[/i][/i]
//写入byte[][i][i]
public void WriteBytes(byte[] buffer)
{
for (int i = 0; buffer != null && i < buffer.Length; i++)
m_Writer.BaseStream.WriteByte(buffer[i]);
}[/i][/i][/i]
//写入byte[] 指定开始及结束位置--相当于截取byte[]中的部分[i][i][i]
public void WriteBytes(byte[] bytes, int offset, int length)
{
for (int i = offset; i < offset + length; i++)
m_Writer.BaseStream.WriteByte(bytes[i]);
}[/i][/i][/i][/i]
//写入double[i][i][i][i]
public void WriteDouble(double value)
{
byte[] bytes = BitConverter.GetBytes(value);
WriteBigEndian(bytes);
}[/i][/i][/i][/i]
//写入float[i][i][i][i]
public void WriteFloat(float value)
{
byte[] bytes = BitConverter.GetBytes(value);
WriteBigEndian(bytes);
}[/i][/i][/i][/i]
//写入高字节序byte[][i][i][i][i]
private void WriteBigEndian(byte[] bytes)
{
if (bytes == null)
return;
for (int i = 0; i < bytes.Length; i++)
{
m_Writer.BaseStream.WriteByte(bytes[i]);
}
}
[/i][/i][/i][/i][/i]//写入int32[i][i][i][i][i]
public void WriteInt32(int value)
{
byte[] bytes = BitConverter.GetBytes(value);
WriteBigEndian(bytes);
}
[/i][/i][/i][/i][/i]//写入int[i][i][i][i][i]
public void WriteInt(int value)
{
WriteInt32(value);
}
[/i][/i][/i][/i][/i]//写入短整型[i][i][i][i][i]
public void WriteShort(int value)
{
byte[] bytes = BitConverter.GetBytes((ushort)value);
WriteBigEndian(bytes);
}
[/i][/i][/i][/i][/i]//写入正整型[i][i][i][i][i]
public void WriteUnsignedInt(uint value)
{
WriteInt32((int)value);
}
[/i][/i][/i][/i][/i]//写入字符串[i][i][i][i][i]
public void WriteUTF(string value)
{
UTF8Encoding utf8Encoding = new UTF8Encoding();
int byteCount = utf8Encoding.GetByteCount(value);
byte[] buffer = utf8Encoding.GetBytes(value);
WriteShort(byteCount);
if (buffer.Length > 0)
m_Writer.Write(buffer);
}
[/i][/i][/i][/i][/i]//写入字符串[i][i][i][i][i]
public void WriteUTFBytes(string value)
{
UTF8Encoding utf8Encoding = new UTF8Encoding();
byte[] buffer = utf8Encoding.GetBytes(value);
if (buffer.Length > 0)
m_Writer.Write(buffer);
}
[/i][/i][/i][/i][/i]//写入带长度的字符串[i][i][i][i][i]
public void WriteStringBytes(string value)
{
UTF8Encoding utf8Encoding = new UTF8Encoding();
byte[] buffer = utf8Encoding.GetBytes(value);
if (buffer.Length > 0)
{
m_Writer.Write(buffer.Length);
m_Writer.Write(buffer);
}
}
}
9、处理服务器反馈回来的消息
public class LoginHandler : MonoBehaviour {
void Start(){}
void Update(){}
public void OnMessage(SocketModel model){
//Debug.Log ("read message...");
switch (model.command){
case LoginProtocol.REG_SRES:
RegResult (model.message);
break;
case LoginProtocol.LOGIN_SRES:
LoginResult (model.message);
break;
}
}
private void RegResult(string message){
Debug.Log (message);
BoolDTO dto = Coding<BoolDTO>.decode(message);
if(dto.value){
WindowConstans.windowList.Add (WindowConstans.ACC_REG_SUCCEED);
}else{
WindowConstans.windowList.Add (WindowConstans.ACC_REG_FAIL);
}
}
private void LoginResult(string message){
StringDTO dto = Coding<StringDTO>.decode (message);
if(dto.value == null || dto.value == string.Empty){
WindowConstans.windowList.Add (WindowConstans.LOGIN_FAIL);
}else{
GameInfo.ACC_ID = dto.value;
//GameInfo.GAME_STATE = GameState.LOADING;
BroadcastMessage ("Loading",1);
}
}
}
public class UserHandler : MonoBehaviour
{
public void OnMessage(SocketModel model){
//Debug.Log (model.message);
switch(model.command){
case UserProtocol.LIST_SRES:
list (model.message);
break;
case UserProtocol.CREATE_SRES:
create (model.message);
break;
case UserProtocol.SELECT_SRES:
selectPlayer (model.message);
break;
}
}
private void selectPlayer(string message){
PlayerModel dto = Coding<PlayerModel>.decode(message);
GameInfo.myModel = dto;
EnterMapDTO edto = new EnterMapDTO();
edto.map = dto.map;
edto.point = dto.point;
edto.rotation = dto.rotation;
string m = Coding<EnterMapDTO>.encode (edto);
NetWorkScript.getInstance().sendMessage(Protocol.MAP, dto.map, MapProtocol.ENTER_CREQ,m);
}
private void create(string message){
if(message == null){
WindowConstans.windowList.Add (WindowConstans.JOB_CREATE_ERROR);
}else{
//WindowConstans.windowList.Add (WindowConstans.JOB_CREATE_SUCCEED);
string m = Coding<StringDTO>.encode (new StringDTO(GameInfo.ACC_ID));
NetWorkScript.getInstance ().sendMessage (Protocol.USER,0,UserProtocol.LIST_CREQ,m);
}
}
private void list(string message){
BroadcastMessage ("cleanButtons");
if(message == null){
for(int i=0; i<2; i++){
CreateButtonModel model = new CreateButtonModel();
model.index = i;
PlayerModel dto = new PlayerModel();
dto.job = 0;
model.player = dto;
BroadcastMessage ("CreatePlayerButton",model);
}
return;
}
PlayerModel[] dtos = Coding<PlayerModel[]>.decode (message);
for(int i=0; i<2; i++){
CreateButtonModel model = new CreateButtonModel();
model.index = i;
if(i > dtos.Length-1){
PlayerModel dto = new PlayerModel();
dto.job = 0;
model.player = dto;
}else{
model.player = dtos[i];
}
BroadcastMessage ("CreatePlayerButton",model);
}
GameInfo.GAME_STATE = GameState.RUN;
}
}
public class MapHandler : MonoBehaviour {
//public GameObject[] pre;
//public GameObject[] mpre;
public GameObject hpUp;
public GameObject levelUpPre;
//private Dictionary<string,MonsterModel> monsterList = new Dictionary<string, MonsterModel>();
//private Dictionary<string,GameObject> monstergoList = new Dictionary<string, GameObject>();
private bool isLoading = false;
public GameObject[] playerProfabs;
private Dictionary<string,PlayerModel> playerList = new Dictionary<string, PlayerModel>();
private Dictionary<string,GameObject> playergoList = new Dictionary<string, GameObject>();
public void OnMessage(SocketModel model){
switch (model.command){
case MapProtocol.ENTER_SRES:
myEnter (model.message);
break;
case MapProtocol.ENTER_BRO:
playerEnter (model.message);
break;
case MapProtocol.MOVE_BRO:
move (model.message);
break;
case MapProtocol.LEAVE_BRO:
leave (model.message);
break;
case MapProtocol.TALK_BRO:
chat (model.message);
break;
case MapProtocol.ATTACK_BRO:
attack (model.message);
break;
case MapProtocol.BE_ATTACE_BRO:
beAttack (model.message);
break;
}
}
public void levelUp(string message){
StringDTO dto = Coding<StringDTO>.decode (message);
playerList[dto.value].level += 1;
playerList[dto.value].exp = 0;
playergoList[dto.value].BroadcastMessage ("levelUp");
GameObject go = playergoList[dto.value];
Instantiate (levelUpPre,new Vector3(go.transform.position.x,go.transform.position.y,go.transform.position.z),new Quaternion(go.transform.rotation.x,go.transform.rotation.y,go.transform.rotation.z,go.transform.rotation.w));
if(dto.value == GameInfo.myModel.id){
gameObject.BroadcastMessage ("infoChange");
}
}
/*
public void relive(string message){
StringDTO dto = Coding<StringDTO>.decode (message);
monsterList[dto.value].hp = monsterList[dto.value].maxHp;
monstergoList[dto.value].BroadcastMessage("relive");
monstergoList[dto.value].collider.enabled = true;
}
*/
/*
public void monsterDie(string message){
StringDTO dto = Coding<StringDTO>.decode (message);
monstergoList[dto.value].BroadcastMessage ("die");
monstergoList[dto.value].collider.enabled = false;
}
*/
/*
void monsterInit(string message){
MonsterModel[] ms = Coding<MonsterMondel>.decode (message);
if(isLoading){
LoadData.getMonsterModels().AddRange(ms);
}
else{
foreach(MonsterModel mm in ms)
{
createMonster(mm);
}
}
}
*/
public void expUp(string message){
Debug.Log("expUp");
IntDTO dto = Coding<IntDTO>.decode (message);
GameInfo.myModel.exp += dto.value;
gameObject.BroadcastMessage ("infoChange");
}
public void beAttack(string message){
BeAtkDTO dto = Coding<BeAtkDTO>.decode (message);
playerList[dto.id].hp -= dto.value;
GameObject go = playergoList[dto.id];
GameObject hp = (GameObject)Instantiate (hpUp,new Vector3(go.transform.position.x,go.transform.position.y+go.transform.collider.bounds.size.y/2,go.transform.position.z),new Quaternion(go.transform.rotation.x,go.transform.rotation.y,go.transform.rotation.z,go.transform.rotation.w));
//hp.BroadcastMessage ("setValue",dto.value);
go.BroadcastMessage ("beAttack",dto.id);
}
private void attack(string message){
AttackDTO dto = Coding<AttackDTO>.decode (message);
if(dto.userId == GameInfo.myModel.id){
GameInfo.PLAYER_STATE = PlayerStateConstans.ATTACK;
}
GameObject go = playergoList[dto.userId];
//go.BroadcastMessage ("SetP",new UnityEngine.Vector3((float)dto.point.X,(float)dto.point.Y,(float)dto.point.Z));
//go.BroadcastMessage ("SetR",new Quaternion((float)dto.Rotation.X,(float)dto.Rotation.Y,(float)dto.Rotation.Z,(float)dto.Rotation.W));
go.BroadcastMessage ("PlayerState",PlayerStateConstans.ATTACK);
}
private void skill(string message){
AttackDTO dto = Coding<AttackDTO>.decode (message);
if(dto.userId == GameInfo.myModel.id){
GameInfo.PLAYER_STATE = PlayerStateConstans.SKILL;
}
GameObject obj = playergoList[dto.userId];
//obj.BroadcastMessage ("SetP",new Vector3((float)dto.point.X,(float)dto.point.Y,(float)dto.point.Z));
//obj.BroadcastMessage ("SetR",new Quaternion((float)dto.Rotation.X,(float)dto.Rotation.Y,(float)dto.Rotation.Z,(float)dto.Rotation.W));
obj.BroadcastMessage ("PlayerState",PlayerStateConstans.SKILL);
}
private void chat(string message){
StringDTO dto = Coding<StringDTO>.decode (message);
BroadcastMessage ("readChat",dto.value);
}
private void leave(string message){
StringDTO dto = Coding<StringDTO>.decode (message);
if(playerList[dto.value]!=null){
playerList.Remove (dto.value);
}
if(playergoList[dto.value]!=null){
GameObject go = playergoList[dto.value];
playergoList.Remove (dto.value);
Destroy(go);
}
}
private void move(string message){
//Debug.Log("player moving!");
MoveDTO dto = Coding<MoveDTO>.decode (message);
if(dto.Id == GameInfo.myModel.id){
return;
}
GameObject go = playergoList[dto.Id];
go.BroadcastMessage ("setR",new Quaternion((float)dto.Rotation.X,(float)dto.Rotation.Y,(float)dto.Rotation.Z,(float)dto.Rotation.W));
go.BroadcastMessage ("setP",new Vector3((float)dto.Point.X,(float)dto.Point.Y,(float)dto.Point.Z));
go.BroadcastMessage ("PlayerState",dto.Dir);
}
private void playerEnter(string message){
PlayerModel player = Coding<PlayerModel>.decode(message);
if(isLoading){
LoadData.loadingPlayerList.Add (player);
}else{
//对此对象进行实例化
createPlayer (player);
//Debug.Log ("createPlayer();");
}
}
private void myEnter(string message){
PlayerModel[] players = Coding<PlayerModel[]>.decode(message);
LoadData.loadingPlayerList.AddRange (players);
isLoading = true;
BroadcastMessage ("Loading",GameInfo.myModel.map);
}
void OnLevelWasLoaded(int level){
if(level < 2){
return;
}
if(level != GameInfo.myModel.map)return;
//开始进行列表解析生成对象
foreach(PlayerModel model in LoadData.loadingPlayerList){
createPlayer (model);
}
LoadData.loadingPlayerList.Clear ();
GameInfo.GAME_STATE = GameState.RUN;
}
private void createPlayer(PlayerModel model){
playerList.Add (model.id, model);
Assets.Model.Vector3 point = model.point;
Assets.Model.Vector4 rotation = model.rotation;
GameObject GO = (GameObject)Instantiate (playerProfabs[model.job],new Vector3((float)point.X,(float)point.Y,(float)point.Z),new Quaternion((float)rotation.X,(float)rotation.Y,(float)rotation.Z,(float)rotation.W));
GO.name = model.id;
GO.tag = "Player";
GO.transform.position =new Vector3(188f,10f,88f);//set position;
playergoList.Add(model.id,GO);
GO.BroadcastMessage ("InfoInit",model);
if(model.id == GameInfo.myModel.id){//make sure our camera wouln't look at other players.
//GameObject tg= GameObject.Find ("Root");
BroadcastMessage ("setTarget",GO);
//BroadcastMessage ("setTarget",tg);
//BroadcastMessage ("InfoInit",model);
}
}
}
消息管理器
public class MessageManager : MonoBehaviour {
private LoginHandler login;
private UserHandler user;
private MapHandler map;
// Use this for initialization
void Start () {
login = GetComponent<LoginHandler>();
user = GetComponent<UserHandler>();
map = GetComponent<MapHandler>();
}
// Update is called once per frame
void Update () {
List<SocketModel> list = NetWorkScript.getInstance().getList();
for(int i=0;i<8;i++){
if(list.Count>0){//........................................
SocketModel model = list[0];
OnMessage(model);
list.RemoveAt (0);
}else{
break;
}
}
}
public void OnMessage(SocketModel model){
switch(model.type){
case Protocol.LOGIN:
login.OnMessage(model);
break;
case Protocol.USER:
user.OnMessage (model);
break;
case Protocol.MAP:
map.OnMessage (model);
break;
default:
WindowConstans.windowList.Add (WindowConstans.SOCKET_TYPE_ERROR);
break;
}
}
}