Unity进阶–通过PhotonServer实现人物选择和多人同步–PhotonServer(四)

文章目录

  • Unity进阶–通过PhotonServer实现人物选择和多人同步–PhotonServer(四)
    • 服务端
    • 客户端

Unity进阶–通过PhotonServer实现人物选择和多人同步–PhotonServer(四)

服务端

  • 服务端结构如下:

    Unity进阶–通过PhotonServer实现人物选择和多人同步–PhotonServer(四)_第1张图片

  • UserModel

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace PhotonServerFirst.Model.User
    {
        public class UserModel
        {
            public int ID;
            public int Hp;
            public float[] Points = new float[] { -4, 1, -2 }; 
            public UserInfo userInfo;
        }
    
        public class UserInfo
        {
            public static UserInfo[] userList = new UserInfo[] {
                new UserInfo(){ ModelID = 0, MaxHp = 100, Attack = 20, Speed = 3 },
                new UserInfo(){ ModelID = 1, MaxHp = 70, Attack = 40, Speed = 4 }
            };
            public int ModelID;
            public int MaxHp;
            public int Attack;
            public int Speed;
        } 
    }
    
    
    • Messaage

      namespace Net
      {
          public class Message
          {
              public byte Type;
              public int Command;
              public object Content;
              public Message() { }
      
              public Message(byte type, int command, object content)
              {
                  Type = type;
                  Command = command;
                  Content = content;
              }
          }
          //消息类型
          public class MessageType
          {
              //unity
              //类型
              public static byte Type_Audio = 1;
              public static byte Type_UI = 2;
              public static byte Type_Player = 3;
              //声音命令
              public static int Audio_PlaySound = 100;
              public static int Audio_StopSound = 101;
              public static int Audio_PlayMusic = 102;
              //UI命令
              public static int UI_ShowPanel = 200;
              public static int UI_AddScore = 201;
              public static int UI_ShowShop = 202;
      
              //网络
              public const byte Type_Account = 1;
              public const byte Type_User = 2;
              //注册账号
              public const int Account_Register = 100;
              public const int Account_Register_Res = 101;
              //登陆
              public const int Account_Login = 102;
              public const int Account_Login_res = 103;
      
              //选择角色
              public const int User_Select = 104; 
              public const int User_Select_res = 105; 
              public const int User_Create_Event = 106;
      
              //删除角色
              public const int User_Remove_Event = 107;
          }
      }
      
      
    • PSPeer

      using System;
      using System.Collections.Generic;
      using Net;
      using Photon.SocketServer;
      using PhotonHostRuntimeInterfaces;
      using PhotonServerFirst.Bll;
      
      namespace PhotonServerFirst
      {
          public class PSPeer : ClientPeer
          {
              public PSPeer(InitRequest initRequest) : base(initRequest)
              {
      
              }
      
              //处理客户端断开的后续工作
              protected override void OnDisconnect(DisconnectReason reasonCode, string reasonDetail)
              {
                  //关闭管理器
                  BLLManager.Instance.accountBLL.OnDisconnect(this);
                  BLLManager.Instance.userBLL.OnDisconnect(this);
              }
      
              //处理客户端的请求
              protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters)
              {
                  PSTest.log.Info("收到客户端的消息");
                  var dic = operationRequest.Parameters;
      
                  //打包,转为PhotonMessage
                  Message message = new Message();
                  message.Type = (byte)dic[0];
                  message.Command = (int)dic[1];
                  List<object> objs = new List<object>();
                  for (byte i = 2; i < dic.Count; i++)
                  {
                      objs.Add(dic[i]);
                  }
                  message.Content = objs.ToArray();
      
                  //消息分发
                  switch (message.Type)
                  {
                      case MessageType.Type_Account:
                          BLLManager.Instance.accountBLL.OnOperationRequest(this, message); 
                          break;
                      case MessageType.Type_User:
                          BLLManager.Instance.userBLL.OnOperationRequest(this, message);
                          break;
                  }
              }
          }
      }
      
      
      • UserBLL

        using Net;
        using PhotonServerFirst.Model.User;
        using PhotonServerFirst.Dal;
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        
        namespace PhotonServerFirst.Bll.User
        {
            class UserBLL : IMessageHandler
            {
                public void OnDisconnect(PSPeer peer)
                {
                    //下线
                    UserModel user = DALManager.Instance.userDAL.GetUserModel(peer);
                    //移除角色
                    DALManager.Instance.userDAL.RemoveUser(peer);
                    //通知其他角色该角色已经下线
                    foreach (PSPeer otherpeer in DALManager.Instance.userDAL.GetuserPeers())
                    {
                        SendMessage.Send(otherpeer, MessageType.Type_User, MessageType.User_Remove_Event, user.ID);
                    }
        
                }
        
                    public void OnOperationRequest(PSPeer peer, Message message)
                {
                    switch (message.Command)
                    {
                        case MessageType.User_Select:
                            //有人选了角色
                            //创建其他角色
                            CreateOtherUser(peer, message);
                            //创建自己的角色
                            CreateUser(peer, message);
                            //通知其他角色创建自己
                            CreateUserByOthers(peer, message); 
                            break;
                    }
                }
        
                    //创建目前已经存在的角色
                    void CreateOtherUser(PSPeer peer, Message message)
                    {
                        //遍历已经登陆的角色
                        foreach (UserModel userModel in DALManager.Instance.userDAL.GetUserModels())
                        {
                            //给登录的客户端响应,让其创建这些角色 角色id 模型id 位置
                            SendMessage.Send(peer, MessageType.Type_User, MessageType.User_Create_Event, userModel.ID, userModel.userInfo.ModelID, userModel.Points);
                        }
                    }
        
                    //创建自己角色
                    void CreateUser(PSPeer peer, Message message)
                    {
                        object[] obj = (object[])message.Content;
                        //客户端传来模型id
                        int modelId = (int)obj[0];
                        //创建角色
                        int userId = DALManager.Instance.userDAL.AddUser(peer, modelId);
                        //告诉客户端创建自己的角色
                        SendMessage.Send(peer, MessageType.Type_User, MessageType.User_Select_res, userId, modelId, DALManager.Instance.userDAL.GetUserModel(peer).Points);
                    }
        
                    //通知其他角色创建自己
                    void CreateUserByOthers(PSPeer peer, Message message)
                    {
                        UserModel userModel = DALManager.Instance.userDAL.GetUserModel(peer);
                        //遍历全部客户端,发送消息
                        foreach (PSPeer otherpeer in DALManager.Instance.userDAL.GetuserPeers())
                        {
                            if (otherpeer == peer)
                            {
                                continue;
                            }
                            SendMessage.Send(otherpeer, MessageType.Type_User, MessageType.User_Create_Event, userModel.ID, userModel.userInfo.ModelID, userModel.Points);
                        }
                }
            }   
         }
        
        
      • BLLManager

        using PhotonServerFirst.Bll.User;
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        
        namespace PhotonServerFirst.Bll
        {
            public class BLLManager
            {
                private static BLLManager bLLManager;
                public static BLLManager Instance
                {
                    get
                    {
                        if(bLLManager == null)
                        {
                            bLLManager = new BLLManager();
                        }
                        return bLLManager;
                    }
                }
                //登录注册管理
                public IMessageHandler accountBLL;
                //角色管理
                public IMessageHandler userBLL;
        
                private BLLManager()
                {
                    accountBLL = new PhsotonServerFirst.Bll.Account.AccountBLL();
                    userBLL = new UserBLL();
                }
        
            }
        }
        
        
        • UserDAL

          using System;
          using System.Collections.Generic;
          using System.Linq;
          using System.Text;
          using PhotonServerFirst.Model.User;
          
          namespace PhotonServerFirst.Dal.User
          {
              class UserDAL
              {
                  //角色保存集合
                  private Dictionary<PSPeer, UserModel> peerUserDic = new Dictionary<PSPeer, UserModel>();
                  private int userId = 1;
          
                  /// 
                  ///添加一名角色
                  /// 
                  /// 连接对象
                  /// 几号角色
                  /// 用户id
                  public int AddUser(PSPeer peer, int index)
                  {
                      UserModel model = new UserModel();
                      model.ID = userId++;
                      model.userInfo = UserInfo.userList[index];
                      model.Hp = model.userInfo.MaxHp;
                      if (index == 1)
                      {
                          model.Points = new float[] { 0, 2, -2 };
                      }
                      peerUserDic.Add(peer, model);
                      return model.ID;
                  }
          
                  ///
                  ///移除一名角色
                  /// 
                  public void RemoveUser(PSPeer peer)
                  {
                      peerUserDic.Remove(peer);
                  }
          
          
                  ///
                  ///得到用户模型
                  ///
                  ///连接对象
                  ///用户模型
                  public UserModel GetUserModel(PSPeer peer){
                       return peerUserDic[peer];
                  }
          
                  ///
                  ///得到全部的用户模型
                  ///
                  public UserModel[] GetUserModels() {
                      return peerUserDic.Values.ToArray();
                  }
          
                  ///
                  ///得到全部有角色的连接对象
                  ///
                  public PSPeer[] GetuserPeers()
                  {
                      return peerUserDic.Keys.ToArray();
                  }
          
              }
          }
          
          
        • DALManager

          using PhotonServerFirst.Bll;
          using PhotonServerFirst.Dal.User;
          using System;
          using System.Collections.Generic;
          using System.Linq;
          using System.Text;
          
          namespace PhotonServerFirst.Dal
          {
              class DALManager
              {
                  private static DALManager dALManager;
                  public static DALManager Instance
                  {
                      get
                      {
                          if (dALManager == null)
                          {
                              dALManager = new DALManager();
                          }
                          return dALManager;
                      }
                  }
                  //登录注册管理
                  public AccountDAL accountDAL;
                  //用户管理
                  public UserDAL userDAL;
          
                  private DALManager()
                  {
                      accountDAL = new AccountDAL();
                      userDAL = new UserDAL();
                  }
              }
          }
          
          

客户端

  • 客户端页面

Unity进阶–通过PhotonServer实现人物选择和多人同步–PhotonServer(四)_第2张图片

  • 绑在panel上

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using Net;
    
    public class SelectPanel : MonoBehaviour
    {
        // Start is called before the first frame update
        void Start()
        {
            
        }
    
        // Update is called once per frame
        void Update()
        {
            
        }
    
        public void SelectHero(int modelId){
            //告诉服务器创建角色
            PhotonManager.Instance.Send(MessageType.Type_User, MessageType.User_Select, modelId);
            //摧毁选择角色页面
            Destroy(gameObject);
            //显示计分版
            UImanager.Instance.SetActive("score", true);
        }
    
    }
    
    
  • 后台持续运行

    Unity进阶–通过PhotonServer实现人物选择和多人同步–PhotonServer(四)_第3张图片

    • 建一个usermanager,绑定以下脚本

      using System.Collections;
      using System.Collections.Generic;
      using UnityEngine;
      using Net;
      
      public class UserManager : ManagerBase 
      {
          void Start(){
              MessageCenter.Instance.Register(this);
          }
      
          public override void ReceiveMessage(Message message){
              base.ReceiveMessage(message);
              //打包
              object[] obs = (object[])message.Content;
              //消息分发
              switch(message.Command){
                  case MessageType.User_Select_res:
                  selectUser(obs);
                  break;
                  case MessageType.User_Create_Event:
                  CreateotherUser(obs);
                  break;
                  case MessageType.User_Remove_Event:
                  RemoveUser(obs);
                  break;
              }
          }  
      
          public override byte GetMessageType(){
              return MessageType.Type_User;
          }
      
          //选择了自己的角色
          void selectUser(object[] objs){
              int userId =(int)objs[0];
              int modelId = (int)objs[1];
              float[] point = (float[])objs[2];
              if (userId > 0)
              {
                  //创建角色
                  GameObject UserPre = Resources.Load<GameObject>("User/" + modelId);
                  UserControll user = Instantiate(UserPre,new Vector3(point[0],point[1],point[2]),Quaternion.identity).GetComponent<UserControll>();
      
                  UserControll.ID =userId;
                  //保存到集合中
                  UserControll.idUserDic.Add(userId, user);
              }
              else {
                  Debug.Log("创建角色失败");
              }
          }
      
          //创建其他角色
          void CreateotherUser(object[] objs){
              //打包
              int userId = (int)objs[0];
              int modelId = (int)objs [1];
              float[] point = (float[])objs[2];
              GameObject UserPre = Resources.Load<GameObject>("User/" + modelId);
              UserControll user = Instantiate(UserPre, new Vector3(point[0],point[1], point[2]),Quaternion.identity).GetComponent<UserControll>();
              UserControll.idUserDic.Add(userId, user);
          }
      
          //删除一名角色
          void RemoveUser(object[] objs){
              int userId = (int)objs[0];
              UserControll user = UserControll.idUserDic[userId];
              UserControll.idUserDic.Remove(userId);
              Destroy(user.gameObject);
          }
      
      
      }
      
      
    • 给物体上绑定

      using System.Collections;
      using System.Collections.Generic;
      using UnityEngine;
      
      public class UserControll : MonoBehaviour
      {
          //保存了所有角色的集合
          public static Dictionary<int, UserControll> idUserDic = new Dictionary<int, UserControll>();
          //当前客户端角色的id
          public static int ID;
          private Animator ani;
      
          // Start is called before the first frame update
          void Start()
          {
              ani = GetComponent<Animator>();
          }
      
          // Update is called once per frame
          void Update()
          {
              
          }
      }
      
      
    • 别忘了按钮绑定

      Unity进阶–通过PhotonServer实现人物选择和多人同步–PhotonServer(四)_第4张图片

你可能感兴趣的:(unity游戏开发,unity,java,游戏引擎)