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

这篇具有很好参考价值的文章主要介绍了Unity进阶–通过PhotonServer实现人物选择和多人同步–PhotonServer(四)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

服务端

  • 服务端结构如下:

    Unity进阶–通过PhotonServer实现人物选择和多人同步–PhotonServer(四),unity游戏开发,unity,java,游戏引擎

  • 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;
          
                  /// <summary>
                  ///添加一名角色
                  /// </summary>
                  /// <param name="peer">连接对象</param>
                  /// <param name="index">几号角色</param>
                  /// <returns>用户id</returns>
                  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;
                  }
          
                  ///<summary>
                  ///移除一名角色
                  /// </summary>
                  public void RemoveUser(PSPeer peer)
                  {
                      peerUserDic.Remove(peer);
                  }
          
          
                  ///<summary>
                  ///得到用户模型
                  ///</summary>
                  ///<param name="peer">连接对象</param>
                  ///<returns>用户模型</returns>
                  public UserModel GetUserModel(PSPeer peer){
                       return peerUserDic[peer];
                  }
          
                  ///<summary>
                  ///得到全部的用户模型
                  ///</summary>
                  public UserModel[] GetUserModels() {
                      return peerUserDic.Values.ToArray();
                  }
          
                  ///<summary>
                  ///得到全部有角色的连接对象
                  ///</summary>
                  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(四),unity游戏开发,unity,java,游戏引擎

  • 绑在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(四),unity游戏开发,unity,java,游戏引擎

    • 建一个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(四),unity游戏开发,unity,java,游戏引擎文章来源地址https://www.toymoban.com/news/detail-660612.html

到了这里,关于Unity进阶–通过PhotonServer实现人物选择和多人同步–PhotonServer(四)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Unity】实用功能开发(一)实现在UI中用RawImage实时展示3D模型(背景透明,并通过UI防止3D场景遮挡)并可以通过分层完成:游戏中的人物状态展示界面,小地图,人物实时头像状态等功能

    有时由于项目效果需要,部分功能的实现受到阻碍,这里收集一些已实现的思路和方法,每次会记录大致需求和遇到的问题,如果有更好的想法,欢迎评论区讨论!!! 目录 功能描述: 需求描述: 实现步骤: ①为需要展示的内容区分层级: ②在场景中添加一个摄像机,并

    2024年02月04日
    浏览(38)
  • Unity 通过鼠标控制模拟人物移动和旋转视角

    要通过鼠标控制并模拟人物移动和转换视角,将会使用射线检测、鼠标点击和鼠标水平移动,配合物体旋转和移动方法共同实现。 首先搭建个由一个Plane地板和若干cube组成的简单场景: 其次创建一个Capsule作为移动物体,并把摄像头拉到该物体中。 创建以下脚本:  把脚本拉

    2024年02月03日
    浏览(35)
  • Unity多人联机的实现

    实现多人联机的方法有几种,具体取决于你的具体需求。以下是一些选项: Unity Multiplayer:Unity有自己的内置网络解决方案,称为Unity Multiplayer(以前称为UNET)。这允许您创建可以在互联网或本地网络上玩的多人游戏。您可以在官方Unity文档中找到有关Unity Multiplayer的更多信息

    2024年02月11日
    浏览(45)
  • git通过fork-merge request实现多人协同

    对于一个项目,如果需要多人协同开发,大家都在原始仓库中进行修改提交,经常会发生冲突,而且一不小心会把别人的代码内容覆盖掉。为了避免这样的问题,git提供了fork-merge request这样的协同方式。 首先git仓库分为远端仓库和本地仓库分别对应上图的remote和local。 sourc

    2024年02月11日
    浏览(24)
  • Unity实现人物旋转+移动

    思路:首先要有个变量去记录下操作前的一个方向状态。(本次操作的对象是正面对着屏幕的。)然后还有有个变量去描述将要发生的方向。接着要明确,前和后,左和右是横跨180°的,其他的两两是相差90°的。所以我们可以以90°一个单位去做旋转。并且利用前面总结的方向

    2024年02月14日
    浏览(37)
  • Unity实现人物移动、旋转、跳跃

    1.Player脚本控制人物移动,可单独使用。(人物需添加组件 Box   Collider和Rigidbody ) 2.相机放在人物头部,转动需要带着人物转,相机转动灵敏度和上下转动角度范围根据具体情况配置。 脚本CameraController和Player直接挂载到人物就可以用了。 3. 文件目录(人物final bowser fly,相

    2024年02月04日
    浏览(31)
  • unity使用PhotonEngine实现多人联机游戏开发(一)

    先来了解一下PhotonEngine(光子引擎),这是德国ExitGame公司开发的网络引擎,photonengine简单易上手,很多游戏公司开发的网络游戏都是使用的这个。这个网络引擎里面包括了PhotonCloud(光子云)、photonServer(光子服务器)、PhotonQuantum(确定性量子引擎)、PhotonVoice(光子语音)

    2024年02月07日
    浏览(44)
  • 〔011〕Stable Diffusion 之 解决绘制多人或面部很小的人物时面部崩坏问题 篇

    相信很多人在画图时候,特别是画 有多个人物 图片或者 人物在图片中很小 的时候,都会很容易出现面部崩坏的问题 这是由于神经网络无法完全捕捉人脸的微妙细节和变化,导致产生了不自然或扭曲的结果 虽然 stable diffusion 在出图的时候自带了一个 面部修复(Restore faces) 按

    2024年02月12日
    浏览(46)
  • Unity mirror实现多人同时在线(LINUX)保姆级

    话不多说直接开始 1 申请服务器(阿里云/腾讯云) 笔者这边直接白嫖的阿里云一个月,测试学习一个月应该是够了。记得重置密码并记录 申请完成后点击左侧目录找到云服务器。记住这个公有服务器,等等会用到。 2 Unity Mirror 坦克大战场景 在NetworkManager找到对应地址,填写

    2024年02月06日
    浏览(57)
  • 实现3D人物的移动和旋转。(Unity)

    首先,需要在人物身上加刚体和碰撞器。   如果需要人物身上有声音,可以添加AudioSource音频源。  然后创建脚本,需要把脚本挂载到对应的对象身上。 如果有动画,还需要创建状态机添加到对应的对象上面,并且设置好里面的动画。  代码实现: 图片实现:     上面代码

    2024年02月04日
    浏览(60)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包