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

文章目录

  • 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.mzph.cn/news/44511.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

八股文之框架篇(Spring Boot、SSM)

文章目录 Spring中的单例bean是线程安全的吗什么是AOP&#xff0c;项目中有没有使用到AOPSpring中的事务是如何实现的Spring中事务失效的场景有哪些Bean的生命周期Spring中的循环依赖&#xff08;循环引用&#xff09;SpringMVC的执行流程SpringBoot自动配置原理Spring、Spring…

Python学习:迭代器与生成器的深入解析

函数在Python中扮演着重要角色&#xff0c;不仅可以封装代码逻辑&#xff0c;还能通过迭代器和生成器这两种强大的技术&#xff0c;实现更高效的数据处理和遍历。本篇博客将深入探讨Python函数的迭代器和生成器&#xff0c;结合实际案例为你揭示它们的神奇&#xff0c;以及如何…

线段树详解——影子宽度

OK&#xff0c;今天来讲一讲线段树~~ 线段树是什么线段树的实现线段树的时间复杂度线段树的应用线段树的节点结构其他操作和优化例题——影子宽度输入输出格式输入格式输出格式 输入输出样例输入样例输出样例 例题讲解 线段树是什么 线段树&#xff08; S e g m e n t Segmen…

C语言实例_解析GPS源数据

一、GPS数据格式介绍 GPS&#xff08;全球定位系统&#xff09;数据格式常见的是NMEA 0183格式&#xff0c;NMEA 0183格式是一种用于导航设备间传输数据的标准格式&#xff0c;定义了一套规范&#xff0c;使得不同厂商的设备可以通过串行通信接口&#xff08;常见的是RS-232&a…

Java 中操作 Redis

文章目录 一、Redis 常用数据类型二、Redis 常用操作命令1. 字符串命令2. 哈希命令3. 列表命令4. 集合命令5. 有序集合命令6. 通用命令 三、在 Java 中操作 Redis1. 导入 maven 坐标2. 配置 Redis 数据源3. 编写配置类 四、在代码中的具体使用 一、Redis 常用数据类型 Redis 存…

连号 区间数

大家好 我是寸铁 希望这篇题解对你有用&#xff0c;麻烦动动手指点个赞或关注&#xff0c;感谢您的关注 不清楚蓝桥杯考什么的点点下方&#x1f447; 考点秘籍 想背纯享模版的伙伴们点点下方&#x1f447; 蓝桥杯省一你一定不能错过的模板大全(第一期) 蓝桥杯省一你一定不…

多IP服务器有什么作用

1.利于搜索引擎收录&#xff1a; 使用多IP应用云服务器可使一个IP对应一个网站&#xff0c;使各个网站之间的独立性更强&#xff0c;这样搜索引擎会评定该网站质量更高&#xff0c; 更容易抓取到该网站的页面&#xff0c;便于搜索引擎收录。 2.提高网站的权重和排名&#xff…

大文本的全文检索方案附件索引

一、简介 Elasticsearch附件索引是需要插件支持的功能&#xff0c;它允许将文件内容附加到Elasticsearch文档中&#xff0c;并对这些附件内容进行全文检索。本文将带你了解索引附件的原理和使用方法&#xff0c;并通过一个实际示例来说明如何在Elasticsearch中索引和检索文件附…

Android13 网络 Adb 默认开启

Android 13 网络 Adb 默认开启 文章目录 Android 13 网络 Adb 默认开启一、前言二、默认adb 代码实现1、修改的目录&#xff1a;2、具体修改&#xff1a;&#xff08;1&#xff09;在XXX_device.mk 添加属性&#xff08;2&#xff09;设置固定端口号&#xff08;3&#xff09;去…

SpringBoot---内置Tomcat 配置和切换

&#x1f600;前言 本篇博文是关于内置Tomcat 配置和切换&#xff0c;希望你能够喜欢 &#x1f3e0;个人主页&#xff1a;晨犀主页 &#x1f9d1;个人简介&#xff1a;大家好&#xff0c;我是晨犀&#xff0c;希望我的文章可以帮助到大家&#xff0c;您的满意是我的动力&#x…

Spring Cloud Alibaba -微服务架构(二)

1. 微服务架构介绍 微服务架构&#xff0c; 简单的说就是将单体应用进一步拆分&#xff0c;拆分成更小的服务&#xff0c;每个服务都是一个可以独立运行的项目。 1.1 微服务架构的常见问题 一旦采用微服务系统架构&#xff0c;就势必会遇到这样几个问题&#xff1a; 这么多小…

测试基金相关的基本信息和常见概念

1、基金&#xff1a; 基金是由投资者共同出资形成的资金池&#xff0c;由专业机构管理和运作。基金公司将这些资金投资于不同的金融工具&#xff0c;如股票、债券、货币市场工具等&#xff0c;以实现共同的投资目标。 2、基金类型&#xff1a; 根据投资策略和资产类别&#…

深入浅出Pytorch函数——torch.nn.init.ones_

分类目录&#xff1a;《深入浅出Pytorch函数》总目录 相关文章&#xff1a; 深入浅出Pytorch函数——torch.nn.init.calculate_gain 深入浅出Pytorch函数——torch.nn.init.uniform_ 深入浅出Pytorch函数——torch.nn.init.normal_ 深入浅出Pytorch函数——torch.nn.init.c…

数据可视化数据调用浅析

数据可视化是现代数据分析和决策支持中不可或缺的一环。它将数据转化为图形、图表和可视化工具&#xff0c;以便更直观地理解和解释数据。在数据可视化的过程中&#xff0c;数据的调用和准备是关键的一步。本文将探讨数据可视化中的数据调用过程&#xff0c;并介绍一些常用的数…

(已解决)PySpark : AttributeError: ‘DataFrame‘ object has no attribute ‘iteritems‘

AttributeError: ‘DataFrame’ object has no attribute ‘iteritems’ 原因在使用SparkSession对象中createDataFrame函数想要将pandas的dataframe转换成spark的dataframe时出现的 因为createDataFrame使用了新版本pandas弃用的iteritems()&#xff0c;所以报错 解决办法&…

city walk结合VR全景,打造新时代下的智慧城市

近期爆火的city walk是什么梗&#xff1f;它其实是近年来备受追捧的城市漫步方式&#xff0c;一种全新的城市探索方式&#xff0c;与传统的旅游观光不同&#xff0c;城市漫步更注重与城市的亲密接触&#xff0c;一步步地感受城市的脉动。其实也是一种自由、休闲的方式&#xff…

Vue的鼠标键盘事件

Vue的鼠标键盘事件 原生 鼠标事件(将v-on简写为) click // 点击 dblclick // 双击 mousedown // 按下 mousemove // 移动 mouseleave // 离开 mouseout // 移出 mouseenter // 进入 mouseover // 鼠标悬浮mousedown.left 键盘事件 keydown //键盘按下时触发 keypress …

Django实现音乐网站 ⑾

使用Python Django框架制作一个音乐网站&#xff0c; 本篇主要是前端开发前的一些必要配置和首页展示开发。 目录 配置应用路由 创建应用路由文件 应用路径加入项目路径 创建项目模板 创建项目及应用模板路径 设置模板路径 设置静态资源路径 创建静态资源路径 配置静态…

thinkphp6前后端验证码分离以及验证

1.验证码接口生成验证码: public function verify(){return captcha(); } 也可以自己写方法 2.验证方法和普通模式session验证有区别,需要改原文件: 修改后的代码: <?php // +---------------------------------------------------------------------- // | ThinkP…

Git commit与pull的先后顺序

Git commit与pull的先后顺序_git先pull再commit_Mordor Java Girl的博客-CSDN博客 ​ 编辑yucoang2020.04.21 回复 28 先pull再commit的话, 你的commit也就不再纯粹了. 这一个commit不再是"你所编辑的xxx功能, 而是"别人所编辑的你所编辑的xxx". 我认为提交历…