Created
          February 12, 2020 16:16 
        
      - 
      
- 
        Save rdeioris/7d21ef7ce0bf975b350dd2314c3ad3cd to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | public class PacketManager : MonoBehaviour | |
| { | |
| [SerializeField] | |
| string address; | |
| [SerializeField] | |
| int port; | |
| [SerializeField] | |
| uint mySelfId = 0; | |
| [SerializeField] | |
| GameObject mySelfObject = null; | |
| [SerializeField] | |
| GameObject enemyPrefab = null; | |
| Dictionary<uint, GameObject> players; | |
| Socket socket; | |
| IPEndPoint serverEndPoint; | |
| byte[] data; | |
| // Start is called before the first frame update | |
| void Start() | |
| { | |
| players = new Dictionary<uint, GameObject>(); | |
| players[mySelfId] = gameObject; | |
| socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); | |
| serverEndPoint = new IPEndPoint(IPAddress.Parse(address), port); | |
| socket.Blocking = false; | |
| data = new byte[16]; | |
| } | |
| // Update is called once per frame | |
| void Update() | |
| { | |
| for (int i = 0; i < 100; i++) | |
| { | |
| int rlen = -1; | |
| try | |
| { | |
| rlen = socket.Receive(data, data.Length, SocketFlags.None); | |
| } | |
| catch | |
| { | |
| break; | |
| } | |
| if (rlen == 16) | |
| { | |
| uint playerId = BitConverter.ToUInt32(data, 0); | |
| float playerX = BitConverter.ToSingle(data, 4); | |
| float playerY = BitConverter.ToSingle(data, 8); | |
| float playerZ = BitConverter.ToSingle(data, 12); | |
| if (playerId == mySelfId) | |
| continue; | |
| Vector3 playerPosition = new Vector3(playerX, playerY, playerZ); | |
| if (!players.ContainsKey(playerId)) | |
| { | |
| GameObject newPlayer = GameObject.Instantiate(enemyPrefab, playerPosition, Quaternion.identity); | |
| newPlayer.GetComponentInChildren<TextMesh>().text = playerId.ToString(); | |
| players[playerId] = newPlayer; | |
| } | |
| else | |
| { | |
| players[playerId].transform.position = playerPosition; | |
| } | |
| } | |
| } | |
| Vector3 myPosition = mySelfObject.transform.position; | |
| byte[] dataId = BitConverter.GetBytes(mySelfId); | |
| byte[] dataX = BitConverter.GetBytes(myPosition.x); | |
| byte[] dataY = BitConverter.GetBytes(myPosition.y); | |
| byte[] dataZ = BitConverter.GetBytes(myPosition.z); | |
| dataId.CopyTo(data, 0); | |
| dataX.CopyTo(data, 4); | |
| dataY.CopyTo(data, 8); | |
| dataZ.CopyTo(data, 12); | |
| socket.SendTo(data, data.Length, SocketFlags.None, serverEndPoint); | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment