Unity进阶–通过PhotonServer实现人物移动和攻击–PhotonServer(五)

Unity进阶–通过PhotonServer实现人物移动和攻击–PhotonServer(五)

DLc: 消息类和通信类

  • Message

    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_UI = 0;
       
            //账号登录注册
            public const byte Type_Account = 1;
            //用户
            public const byte Type_User = 2;
            //攻击
            public const byte Type_Battle = 3;
    
            //注册账号
            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 = 204; 
            public const int User_Select_res = 205; 
            public const int User_Create_Event = 206;
            //删除角色
            public const int User_Remove_Event = 207;
    
            //攻击和移动
            //移动point[]
            public const int Battle_Move = 301;
            //移动响应id point[]
            public const int Battle_Move_Event = 302;
            //攻击 targetid
            public const int Battle_Attack = 303;
            //攻击响应id targetid 剩余血量
            public const int Battle_Attack_Event = 304;
    
    
        }
    }
    
    
    • peer类

      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:
                          //PSTest.log.Info("收到客户端的登陆消息");
                          BLLManager.Instance.accountBLL.OnOperationRequest(this, message); 
                          break;
                      case MessageType.Type_User:
                          BLLManager.Instance.userBLL.OnOperationRequest(this, message);
                          break;
                      case MessageType.Type_Battle:
                          PSTest.log.Info("收到攻击移动命令");
                          BLLManager.Instance.battleMoveBLL.OnOperationRequest(this, message);
                          break;
                  }
              }
          }
      }
      
      
  • 客户端对接类

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using ExitGames.Client.Photon;
    using Net;
    
    public class PhotonManager : MyrSingletonBase<PhotonManager>, IPhotonPeerListener
    {
          
          
        private  PhotonPeer peer;
        
        void Awake() {
          
          
            base.Awake();
            DontDestroyOnLoad(this);
        }
        // Start is called before the first frame update
        void Start()
        {
          
          
            peer = new PhotonPeer(this, ConnectionProtocol.Tcp);
            peer.Connect("127.0.0.1:4530", "PhotonServerFirst");
        }
    
        void Update()
        {
          
          
            peer.Service();
        }
    
        private void OnDestroy() {
          
          
            base.OnDestroy();
            //断开连接
            peer.Disconnect();    
        }
    
        public void DebugReturn(DebugLevel level, string message)
        {
          
          
    
        }
    
        /// <summary>
        /// 接收服务器事件
        /// </summary>
        /// <param name="eventData"></param>
        public void OnEvent(EventData eventData)
        {
          
          
            
            //拆包
            Message msg = new Message();
            msg.Type = (byte)eventData.Parameters[0];
            msg.Command = (int)eventData. Parameters[1];
            List<object> list = new List<object>();
            for (byte i = 2; i < eventData.Parameters.Count; i++){
          
          
                list.Add(eventData.Parameters[i]);
            }
            msg.Content = list.ToArray();
            MessageCenter.SendMessage(msg);
        }
    
        /// <summary>
        /// 接收服务器响应
        /// </summary>
        /// <param name="operationResponse"></param>
        public void OnOperationResponse(OperationResponse operationResponse)
        {
          
          
            if (operationResponse.OperationCode == 1){
          
          
                Debug.Log(operationResponse.Parameters[1]);
            }
    
        }
    
        /// <summary>
        /// 状态改变
        /// </summary>
        /// <param name="statusCode"></param>
        public void OnStatusChanged(StatusCode statusCode)
        {
          
          
            Debug.Log(statusCode);
        }
    
        /// <summary>
        /// 发送消息
        /// </summary>
        public void Send(byte type, int command, params object[] objs)
        {
          
          
            Dictionary<byte, object> dic = new Dictionary<byte,object>();
            dic.Add(0,type);
            dic.Add(1,command);
            byte i = 2;
            foreach (object o in objs){
          
          
                dic.Add(i++, o);
            }
            peer.OpCustom(0, dic, true);
        }
    
    }
    
    

服务器

  • BLL管理

    using PhotonServerFirst.Bll.BattleMove;
    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;
            //移动和攻击管理
            public IMessageHandler battleMoveBLL;
        private BLLManager()
        {
          
          
            accountBLL = new PhsotonServerFirst.Bll.Account.AccountBLL();
            userBLL = new UserBLL();
            battleMoveBLL = new BattleMoveBLL();
        }
    
    }
    

    }

  • 移动BLL

    using Net;
    using PhotonServerFirst.Dal;
    using PhotonServerFirst.Model.User;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace PhotonServerFirst.Bll.BattleMove
    {
          
          
        class BattleMoveBLL : IMessageHandler
        {
          
          
            public void OnDisconnect(PSPeer peer)
            {
          
          
                
            }
    
            public void OnOperationRequest(PSPeer peer, Message message)
            {
          
          
                object[] objs = (object[])message.Content; 
                switch (message.Command)
                {
          
          
                    case MessageType.Battle_Move:
                        PSTest.log.Info("BattleMove收到移动命令");
                        Move(peer, objs);
                        break;
                    case MessageType.Battle_Attack:
                        Attack(peer, objs);
                        break;
                }
    
            }
    
            private void Attack(PSPeer peer, object[] objs)
            {
          
          
                //targetid
                //id targetid 剩余血量
                int targetid = (int)objs[0];
                //攻击者
                UserModel user = DALManager.Instance.userDAL.GetUserModel(peer);
                //被攻击者
                UserModel targetUser = DALManager.Instance.userDAL.GetUserModel(targetid);
                //计算伤害
                targetUser.Hp -= user.userInfo.Attack;
                foreach (PSPeer otherpeer in DALManager.Instance.userDAL.GetuserPeers())
                {
          
          
                    SendMessage.Send(otherpeer, MessageType.Type_Battle, MessageType.Battle_Attack_Event, user.ID, targetUser.ID, targetUser.Hp);
                }
            }
    
                private void Move(PSPeer peer, object[] objs)
                {
          
          
                    //位置
                    float[] points = (float[])objs[0];
                    //将要移动的客户端
                    UserModel user = DALManager.Instance.userDAL.GetUserModel(peer); 
                    user.Points = points;
                    //通知所有客户端移动
                    foreach (PSPeer otherpeer in DALManager.Instance.userDAL.GetuserPeers())
                    {
          
          
                    PSTest.log.Info("通知所有客户端移动");
                        SendMessage.Send(otherpeer, MessageType.Type_Battle, MessageType.Battle_Move_Event, user.ID, points);
    
                    }
                }
        }
    }
    
    

客户端

  • 逻辑类

    using System.Collections;
    using System.Collections.Generic;
    using Net;
    using UnityEngine;
    
    public class BattleManager : ManagerBase
    {
          
          
        void Start() {
          
          
            MessageCenter.Instance.Register(this);
        }
        private UserControll user;
        public UserControll User{
          
          
            get{
          
          
                if (user == null){
          
          
                    user = UserControll.idUserDic[UserControll.ID];
                }
                return user;
            }
        }
    
        void Update()
        {
          
          
            if (Input.GetMouseButtonDown(0)){
          
          
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;
                bool res = Physics.Raycast(ray, out hit);
                if (res)
                {
          
          
                    if (hit.collider.tag =="Ground"){
          
          
                        //Debug.Log("点击到地面");
                        //移动到hit.point
                        PhotonManager.Instance.Send(MessageType.Type_Battle, MessageType.Battle_Move, new float[] {
          
           hit.point.x,hit.point.y, hit.point.z });
                        //Debug.Log(hit.point);
                    }
                    if (hit.collider.tag =="User"){
          
          
                        //Debug.Log("点击到玩家");
                        //获取距离
                        float dis = Vector3.Distance(hit.collider.transform.position, User.transform.position);
                        if (dis > 0 && dis < 3f){
          
          
                            UserControll targetUser = hit.collider.GetComponent<UserControll>();
                            PhotonManager.Instance.Send(MessageType.Type_Battle, MessageType.Battle_Attack, targetUser.id);
                        }
                    }
               }
            }
        }
    
        public override void ReceiveMessage(Message message){
          
          
            base.ReceiveMessage(message);
            object[] objs = (object[])message.Content;
            switch (message. Command)
            {
          
          
                case MessageType.Battle_Move_Event:
                Debug.Log("移动");
                    Move(objs);
                    break;
                case MessageType.Battle_Attack_Event:
                    Attack(objs);
                    break;
            }
        }
    
    
        //移动
        void Move(object[] objs){
          
          
            //移动的用户id
            int userid = (int)objs[0];
            //移动的位置
            float[] points = (float[])objs[1];
            UserControll.idUserDic[ userid].Move(new Vector3(points[0],points[1],points[2]));
        }
    
        public override byte GetMessageType(){
          
          
            return MessageType.Type_Battle;
        }
    
        public void Attack(object[] objs){
          
          
            //攻击者id被攻击者id 当前剩余血量
            int userid = (int)objs[0];
            int targetid = (int)objs[1];
            int hp = (int)objs[2];
            //攻击
            UserControll.idUserDic[userid].Attack(targetid);
            if (hp <= 0)
            {
          
          
                UserControll.idUserDic[targetid].Die();
            }
        }
    
    }
    
    
  • 角色绑定的类

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.AI;
    
    public class UserControll : MonoBehaviour
    {
          
          
        //保存了所有角色的集合
        public static Dictionary<int, UserControll> idUserDic = new Dictionary<int, UserControll>();
        //当前客户端角色的id
        public static int ID;
        private Animator ani;
        //private NavMeshAgent agent;
        //目标位置
        private Vector3 targetPos;
        private bool isRun;
        //角色id
        public int id;
        private bool isDie;
    
        // Start is called before the first frame update
        void Start()
        {
          
          
            ani = GetComponent<Animator>();
            //agent = GetComponent<NavMeshAgent>();
        }
    
        // Update is called once per frame
        void Update()
        {
          
          
            if(isDie){
          
          
                return;
            }
            if (isRun){
          
          
                //计算距离
                float dis = Vector3.Distance(transform. position,targetPos);
                if (dis > 0.5f)
                {
          
          
                    //移动
                    //agent.isStopped = false;
                   // ani.SetBoo1( "IsRun", true);
                    //agent.SetDestination(targetPos);
                    transform.position = targetPos;
                }
                else
                {
          
          
                    //停止
                    //agent.isStopped = true;
                   // ani.setBoo1("IsRun", false);
                    isRun = false;
                }
            }
    
        }
        public void Move(Vector3 target){
          
          
            targetPos = target;
            isRun = true;
        }
    
        public void Attack( int targetId){
          
          
            //获得要攻击的角色
            UserControll targetUser = idUserDic[targetId];
            transform.LookAt(targetUser.transform);
            //ani.SetTrigger( "Attack");
        }
    
        public void Die(){
          
          
            //ani. setTrigger("Die");
            isDie = true;
        }
    
    }
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.AI;
    
    public class UserControll : MonoBehaviour
    {
          
          
        //保存了所有角色的集合
        public static Dictionary<int, UserControll> idUserDic = new Dictionary<int, UserControll>();
        //当前客户端角色的id
        public static int ID;
        private Animator ani;
        //private NavMeshAgent agent;
        //目标位置
        private Vector3 targetPos;
        private bool isRun;
        //角色id
        public int id;
        private bool isDie;
    
        // Start is called before the first frame update
        void Start()
        {
          
          
            ani = GetComponent<Animator>();
            //agent = GetComponent<NavMeshAgent>();
        }
    
        // Update is called once per frame
        void Update()
        {
          
          
            if(isDie){
          
          
                return;
            }
            if (isRun){
          
          
                //计算距离
                float dis = Vector3.Distance(transform. position,targetPos);
                if (dis > 0.5f)
                {
          
          
                    //移动
                    //agent.isStopped = false;
                   // ani.SetBoo1( "IsRun", true);
                    //agent.SetDestination(targetPos);
                    transform.position = targetPos;
                }
                else
                {
          
          
                    //停止
                    //agent.isStopped = true;
                   // ani.setBoo1("IsRun", false);
                    isRun = false;
                }
            }
    
        }
        public void Move(Vector3 target){
          
          
            targetPos = target;
            isRun = true;
        }
    
        public void Attack( int targetId){
          
          
            //获得要攻击的角色
            UserControll targetUser = idUserDic[targetId];
            transform.LookAt(targetUser.transform);
            //ani.SetTrigger( "Attack");
        }
    
        public void Die(){
          
          
            //ani. setTrigger("Die");
            isDie = true;
        }
    
    }
    
    

猜你喜欢

转载自blog.csdn.net/abaidaye/article/details/132379864