unity学习(69)——多人位置同步

简单的很,每个客户端向服务器发送位置信息,服务器再把这些位置信息发送给其他客户端

1.客户端发送。

1.1在SocketModel脚本中添加一个新的类MoveDTO

cs 复制代码
public class MoveDTO
{
	public string Id{get; set;}
	public int Dir{get;set;}
	public Assets.Model.Vector4 Rotation{get;set;}
	public Assets.Model.Vector3 Point{get;set;}
}

一个新的PlayerStateConstans类

cs 复制代码
public class PlayerStateConstans
{
	public const int FORWARD=0;
	public const int BACK=1;
	public const int LEFT=2;
	public const int RIGHT=3;
	public const int IDLE=4;
	public const int ATTACK=5;
	public const int SKILL=6;
	public const int DIE=7;
}

1.2在JoystickPlayerExample脚本中的FixedUpdate()中添加如下代码,不停的向服务器发包。

cs 复制代码
MoveDTO dto = new MoveDTO();
dto.Id = SelectMenu.nowPlayer.id;
dto.Dir = PlayerStateConstans.IDLE;//玩家的状态,这个到时候去服务器翻一下--playerState结构体
dto.Rotation = new Assets.Model.Vector4( model.transform.rotation);//转码啥的都只是时间问题
dto.Point = new Assets.Model.Vector3( model.transform.position);//系统自带的
string message = LitJson.JsonMapper.ToJson(dto);
NetWorkScript.getInstance().sendMessage(Protocol.MAP,SelectMenu.nowPlayer.map,MapProtocol.MOVE_CREQ,message);

1.3从双端的执行结果,服务器此时应该是成功解析了数据包并发回了其他玩家的信息,这个里编译测试应该是不远了。

2.通过上图可见,返回的结果数据包的三个参数是 1 2 4,在mapHandler增加对于command=4的处理代码,处理返回所有角色的移动信息,包括我自己

2.1在MessageManager脚本的MapHandlerFk中增加代码

2.2给预制体模型挂在一个脚本EachStateScript,用来存放每个实例化模型包含的状态变量,内容如下:这个变量可不能用static,静态变量连赋值都做不到。

2.3MapHandler.cs中增加move函数,解析数据包 同时操作对应模型移动,当然不移动自己

百度AI现在真的是强无敌啊!

代码如下:

cs 复制代码
public void move(string message)
{
    MoveDTO dto = Coding<MoveDTO>.decode(message);//感觉马上就要能编译了
    if (dto.Id == SelectMenu.nowPlayer.id)//自己的位置不修改
    {
        return;
    }
    //下面修改实例
    GameObject go = playergoList[dto.Id];
    go.transform.rotation = new Quaternion((float)dto.Rotation.X, (float)dto.Rotation.Y, (float)dto.Rotation.Z, (float)dto.Rotation.W);
    go.transform.position = new Vector3((float)dto.Point.X, (float)dto.Point.Y, (float)dto.Point.Z);
    //go.BroadcastMessage("PlayerState", dto.Dir);//这里必须学会给每个实例带上这个状态位
    //go.GetComponent<>
    EachStateScript e = GetComponent<EachStateScript>();
    e.playerState = (int)dto.Dir;
}
相关推荐
sealaugh321 小时前
aws(学习笔记第四十八课) appsync-graphql-dynamodb
笔记·学习·aws
水木兰亭2 小时前
数据结构之——树及树的存储
数据结构·c++·学习·算法
鱼摆摆拜拜2 小时前
第 3 章:神经网络如何学习
人工智能·神经网络·学习
aha-凯心2 小时前
vben 之 axios 封装
前端·javascript·学习
ytttr8736 小时前
matlab通过Q学习算法解决房间路径规划问题
学习·算法·matlab
听风ツ9 小时前
固高运动控制
学习
西岭千秋雪_9 小时前
Redis缓存架构实战
java·redis·笔记·学习·缓存·架构
XvnNing9 小时前
【Verilog硬件语言学习笔记4】FPGA串口通信
笔记·学习·fpga开发
牛奶咖啡1310 小时前
学习设计模式《十六》——策略模式
学习·设计模式·策略模式·认识策略模式·策略模式的优缺点·何时选用策略模式·策略模式的使用示例
The_cute_cat10 小时前
JavaScript的初步学习
开发语言·javascript·学习