Created
February 8, 2019 18:55
-
-
Save rdeioris/2b0fd20ab83128421c8c2b882f58433d 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
| using System.Collections; | |
| using System.Collections.Generic; | |
| using UnityEngine; | |
| using System; | |
| using System.Net; | |
| using System.Net.Sockets; | |
| public class GameClient : MonoBehaviour | |
| { | |
| [SerializeField] | |
| private string address; | |
| [SerializeField] | |
| private int port; | |
| [SerializeField] | |
| private GameObject objectToMove; | |
| private Socket socket; | |
| private IPEndPoint endPoint; | |
| // Start is called before the first frame update | |
| void Start() | |
| { | |
| socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); | |
| socket.Blocking = false; | |
| endPoint = new IPEndPoint(IPAddress.Parse(address), port); | |
| // prepare and send the join packet | |
| byte[] joinPacket = new byte[1]; | |
| joinPacket[0] = 0; | |
| socket.SendTo(joinPacket, endPoint); | |
| } | |
| // Update is called once per frame | |
| void Update() | |
| { | |
| DequeuePackets(); | |
| UpdateVelocity(); | |
| } | |
| void DequeuePackets() | |
| { | |
| byte[] receivedPacket = new byte[64]; | |
| int rlen = 0; | |
| try | |
| { | |
| rlen = socket.Receive(receivedPacket); | |
| if (rlen != 13) | |
| return; | |
| // UPDATE LOCATION | |
| if (receivedPacket[0] == 2) | |
| { | |
| float x = BitConverter.ToSingle(receivedPacket, 1); | |
| float y = BitConverter.ToSingle(receivedPacket, 5); | |
| float z = BitConverter.ToSingle(receivedPacket, 9); | |
| objectToMove.transform.position = new Vector3(x, y, z); | |
| } | |
| } | |
| catch | |
| { | |
| return; | |
| } | |
| } | |
| void UpdateVelocity() | |
| { | |
| byte[] setVelocityPacket = new byte[13]; | |
| setVelocityPacket[0] = 1; | |
| byte[] velocityX; | |
| byte[] velocityY; | |
| byte[] velocityZ; | |
| if (Input.GetKey(KeyCode.Space)) | |
| { | |
| velocityX = BitConverter.GetBytes(0.0f); | |
| velocityY = BitConverter.GetBytes(0.0f); | |
| velocityZ = BitConverter.GetBytes(3.0f); | |
| } | |
| else | |
| { | |
| velocityX = BitConverter.GetBytes(0.0f); | |
| velocityY = BitConverter.GetBytes(0.0f); | |
| velocityZ = BitConverter.GetBytes(0.0f); | |
| } | |
| Buffer.BlockCopy(velocityX, 0, setVelocityPacket, 1, 4); | |
| Buffer.BlockCopy(velocityY, 0, setVelocityPacket, 5, 4); | |
| Buffer.BlockCopy(velocityZ, 0, setVelocityPacket, 9, 4); | |
| socket.SendTo(setVelocityPacket, endPoint); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment