/// <summary> /// udp数据包解析函数 /// </summary> /// <param name="buf">字节数组</param> private void Parse(byte[] buf) { MsgType msgType = MsgType.None; Msg msg = null; string str = Encoding.UTF32.GetString(buf); string[] strs = str.Split('|'); msgType = (MsgType)Convert.ToInt32(strs[0]); //通过不同的消息类型,对消息进行解析 switch (msgType) { case MsgType.TankNew: msg = new TankNewMsg(ctrl); msg.Parse(buf); break; case MsgType.TankMove: msg = new TankMoveMsg(ctrl); msg.Parse(buf); break; case MsgType.BulletNew: msg = new BulletNewMsg(ctrl); msg.Parse(buf); break; } }
private void TankMove(Tank tank) { dirOld = tank.Dir; if (tank.Dir != Direction.Stop) { tank.DirOld = tank.Dir; } if (dirUp) { tank.Dir = Direction.Up; tank.Move(); } if (dirDown) { tank.Dir = Direction.Down; tank.Move(); } if (dirLeft) { tank.Dir = Direction.Left; tank.Move(); } if (dirRight) { tank.Dir = Direction.Right; tank.Move(); } if (!dirUp && !dirDown && !dirLeft && !dirRight) { tank.Dir = Direction.Stop; } //与边界的碰撞检测 if (tank.X < 0 || tank.Y < 0 || tank.X > gameWidth - Tank.size.Width || tank.Y > gameHeight - Tank.size.Height) { myTank.X = myTank.XOld; myTank.Y = myTank.YOld; tank.Dir = Direction.Stop; } //与坦克的碰撞检测 for (int i = 0; i < tanks.Count; i++) { if (myTank != null && CollisionDetection(tanks[i].GetRectangle(), myTank.GetRectangle())) { myTank.X = myTank.XOld; myTank.Y = myTank.YOld; tank.Dir = Direction.Stop; } } //与地图物块的碰撞检测 int tmpX = myTank.X / tis.Width; int tmpY = myTank.Y / tis.Height; for (int i = tmpX - 1; i < tmpX + 3; i++) { for (int j = tmpY - 1; j < tmpY + 3; j++) { if (i < 0 || j < 0 || i >= mapWidth || j >= mapHeight) { continue; } if (map[i, j] != null) { if (CollisionDetection(map[i, j].GetRectangle(), myTank.GetRectangle())) { myTank.X = myTank.XOld; myTank.Y = myTank.YOld; tank.Dir = Direction.Stop; } } } } //改变方向时发包 if (nc != null && tank.Dir != dirOld) { TankMoveMsg msg = new TankMoveMsg(tank.Name, tank.X, tank.Y, tank.Dir); nc.Send(msg); } }