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

这篇具有很好参考价值的文章主要介绍了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();
            }
        }
    
    }
    
    
  • 角色绑定的类文章来源地址https://www.toymoban.com/news/detail-660331.html

    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;
        }
    
    }
    
    

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

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

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

相关文章

  • unity进阶学习笔记:photonServer测试

    photonServer是由photon发布的一个网络框架,其封装了UDP和TCP通信机制让用户可以直接调用API实现网络游戏通信 1 photonServer下载安装 进入Photon官网的SDK选项,选择下载Server。目前Server版本已经更新到v5,这里我为了和教程保持一致下载的是老版本v4.下载完后按照安装指引安装即可

    2024年02月04日
    浏览(30)
  • 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)
  • 实现3D人物的移动和旋转。(Unity)

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

    2024年02月04日
    浏览(60)
  • Unity CharacterController控制人物移动(包括重力实现)

    提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 在使用CharacterController组件时,人物移动一般有两种方式,一种是无重力移动–SimpleMove,一种是有重力移动–Move。而使用有重力移动时,又会出现人在下楼梯时无法贴合地面,从而造成飞天效果,最终导

    2024年02月11日
    浏览(29)
  • Unity教程2:保姆级教程.几行代码实现输入控制2D人物的移动

    目录 人物的创建以及刚体的设置 图层渲染层级设置 角色碰撞箱设置 使用代码控制人物移动 创建脚本文件  初始函数解释 控制移动代码 初始化变量  获得键盘输入  调用函数 手册链接在这:Unity User Manual (2019.3) - Unity 手册 没有控制人物移动的2D游戏就太说不过去了!那么接

    2024年02月06日
    浏览(35)
  • 用Unity3D制作FPS游戏的学习笔记————人物移动、利用鼠标实现视角转动和人物跳跃(含人物悬空不掉落修复)

    前言: 这是我第一次发布文章,此文章仅供参考,我也是刚学习接触untiy,在制作项目的过程中将有用的写下来记一记,以便自己之后能回头看看,各位大佬轻点喷,若有错误请麻烦积极提谢谢各位。该文章参考自B站UP主蔡先森_rm-rf发布的 【第一人称射击游戏教程2.0【已完结

    2024年04月27日
    浏览(47)
  • 【unity造车轮】3种实现虚拟移动摇杆控制人物移动的方法(实操加详细讲解,全网最全最易理解)

    素材 继承ScrollRect,自己手戳代码,我愿意称之为最简单的实现

    2024年02月14日
    浏览(32)
  • Unity 原神人物移动和镜头处理

    每帧都处理的地方 不要用 SetTrigger 为什么呢? 你肯定会希望 SetTrigger run 就跑步 SetTrigger stop 就停止 但事实并非如此 SetTrigger 会在下一帧自动设置回去 而你移动肯定是每帧都在 SetTrigger 所以人物移动会抽搐 最好的办法是 设置float 分析原神的镜头 界面左侧负责控制人物移动

    2024年02月07日
    浏览(33)
  • Unity Animator人物模型动画移动偏移

    模型动画出现移动方向偏移 !修改Animation中的Root Transform Rotation(根变换位置)、Root Transform Rotation(x,y,z)(旋转),Bake Info Pose修改为Original。可以解决 !!但是,使用动画移动函数时将无法移动,原因是锁定根变换位置和循环位置 !!!所以只要修改依据为原始或者微调偏离值,

    2024年02月15日
    浏览(33)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包