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

news/2024/11/21 1:35:19/

文章目录

  • Unity进阶–通过PhotonServer实现人物移动和攻击–PhotonServer(五)
    • DLc: 消息类和通信类
    • 服务器
    • 客户端

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;//攻击 targetidpublic 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;//打包,转为PhotonMessageMessage 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 updatevoid 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.pointPhotonManager.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){//移动的用户idint 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>();//当前客户端角色的idpublic static int ID;private Animator ani;//private NavMeshAgent agent;//目标位置private Vector3 targetPos;private bool isRun;//角色idpublic int id;private bool isDie;// Start is called before the first frame updatevoid Start(){ani = GetComponent<Animator>();//agent = GetComponent<NavMeshAgent>();}// Update is called once per framevoid 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>();//当前客户端角色的idpublic static int ID;private Animator ani;//private NavMeshAgent agent;//目标位置private Vector3 targetPos;private bool isRun;//角色idpublic int id;private bool isDie;// Start is called before the first frame updatevoid Start(){ani = GetComponent<Animator>();//agent = GetComponent<NavMeshAgent>();}// Update is called once per framevoid 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;}}

http://www.ppmy.cn/news/1044128.html

相关文章

力扣75——单调栈

总结leetcode75中的单调栈算法题解题思路。 上一篇&#xff1a;力扣75——区间集合 力扣75——单调栈 1 每日温度2 股票价格跨度1 - 2 解题总结 1 每日温度 题目&#xff1a; 给定一个整数数组 temperatures &#xff0c;表示每天的温度&#xff0c;返回一个数组 answer &…

「UG/NX」Block UI 面收集器FaceCollector

✨博客主页何曾参静谧的博客📌文章专栏「UG/NX」BlockUI集合📚全部专栏「UG/NX」NX二次开发「UG/NX」BlockUI集合「VS」Visual Studio「QT」QT5程序设计「C/C+&#

Codeforces Round 153 (Rated for Div. 2)

目录 A. Not a Substring 题目&#xff1a; 解析&#xff1a; B. Fancy Coins 题目&#xff1a; 解析&#xff1a; C. Game on Permutation 题目&#xff1a; 解析&#xff1a; A. Not a Substring 题目&#xff1a; A bracket sequence is a string consisting of ch…

2023全网Mysql 合集(25w字)附课程 从安装到高级,实战

mysql学习 1.安装mysql 安装教程 2.mysql的详细学习教程 mysql的详细教程 3.mysql 的高级优化 MySQL高级篇&#xff08;SQL优化、索引优化、锁机制、主从复制&#xff09; 4.MySQL 面试 MySQL数据库面试题总结 二.mysql实战 一、创建数据表并插入数据 1、学生表 Stud…

LeetCode450. 删除二叉搜索树中的节点

450. 删除二叉搜索树中的节点 文章目录 [450. 删除二叉搜索树中的节点](https://leetcode.cn/problems/delete-node-in-a-bst/)一、题目二、题解方法一&#xff1a;递归&#xff08;一种麻烦的方法&#xff09;方法二&#xff1a;优化后的递归 一、题目 给定一个二叉搜索树的根…

ZZULIOJ 1193: 单科成绩排序(结构体专题),Java

ZZULIOJ 1193: 单科成绩排序&#xff08;结构体专题&#xff09;&#xff0c;Java 题目描述 有一学生成绩表&#xff0c;包括学号、姓名、3门课程成绩。请按要求排序输出&#xff1a;若输入1&#xff0c;则按第1门课成绩降序输出成绩表&#xff0c;若输入为i&#xff08;1<…

VS2015打开Qt的pro项目文件 报错

QT报错&#xff1a;Project ERROR: msvc-version.conf loaded but QMAKE_MSC_VER isn‘t set 解决方法&#xff1a; 找到本机安装的QT路径&#xff0c;找到“msvc-version.conf”文件&#xff0c;用记事本打开&#xff0c; 在其中添加版本“QMAKE_MSC_VER 1900”保存即可。 …