Unity下使用c#进行UDP通信

前言

需要验证一下Unity和UDP的通信。通过Udp发送不同命令,让Unity中创建的方块前后左右移动来验证。

可以通过Unity入门教程(上)快速上手Unity。里面创建了一个方块,并添加了C#代码使方块能够跳起来。有这些入门只是就够了。不用看啰啰嗦嗦的视频是真的好(这里只是想表达如果想快速上手Unity但没空或不方便看视频的情况,这种一篇文字就能明白的干货是真棒。不排除有很多优秀视频的)。

入手了之后,还需要API查询在这里:Unity API,还是中文的。

给方块上了色,摄像机挪到了头顶,现在看起来是这个样子

代码控制

修改了下代码,现在使用键盘(WASD)可以控制前后移动。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    Rigidbody mRigidbody;
    protected float mSpeed = 5f; // 速度

    // Start is called before the first frame update
    void Start()
    {
        mRigidbody = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        // 左右移动
        //Store user input as a movement vector
        Vector3 mInput = new Vector3(Input.GetAxis("Horizontal")*10, 0, Input.GetAxis("Vertical")*10);
        //Apply the movement vector to the current position, which is
        //multiplied by deltaTime and speed for a smooth MovePosition
        mRigidbody.MovePosition(transform.position + mInput * Time.deltaTime * mSpeed);

    }

}

现在需要做的就是,实现c# 中的UDP 客户端,收到消息后使用 MovePosition移动即可。

完整代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

public class Player : MonoBehaviour
{
    Rigidbody mRigidbody;
    protected float mSpeed = 25f; // 速度,决定一次的移动长度

    private int port = 9000;
    static Socket server;
    private UdpClient client; // 客户端
    private IPEndPoint remotePoint;
    private Thread thread = null;
    private string receiveString = null;



    // Start is called before the first frame update
    void Start()
    {
        mRigidbody = GetComponent<Rigidbody>();
        // socket 配置,使用线程接收数据
        remotePoint = new IPEndPoint(IPAddress.Loopback, 0);
        thread = new Thread(ReceiveData);
        thread.Start();
    }

    // Update is called once per frame
    void Update()
    {

        if (!string.IsNullOrEmpty(receiveString))
        {
            char a = receiveString.ToUpper().ToCharArray()[0];

            // 左右移动
            int x=0, y=0;
            switch (a) { 
                case 'W':
                    y = 1;
                    break;
                case 'A':
                    x = -1;
                    break;
                case 'S':
                    y = -1;
                    break;
                case 'D':
                    x = 1;
                    break;
            
            }
            
            Vector3 mInput = new Vector3(x, 0, y);
            mRigidbody.MovePosition(transform.position + mInput * Time.deltaTime * mSpeed);


            receiveString = null;
        }

    }

    private void ReceiveData()
    {
        while (true)
        {
            if (string.IsNullOrEmpty(receiveString))
            {
                try
                {
                    //  Setup UDP client.
                    client = new UdpClient(port);

                    //  Grab the data.
                    byte[] data = client.Receive(ref remotePoint);
                    receiveString = Encoding.UTF8.GetString(data);
                    Debug.Log(data.Length);
                    client.Close();

                }
                catch (System.Exception e)
                {
                    Debug.Log(e.ToString());
                }
            }
        }
    }

    
    void OnApplicationQuit() 
    {
        SocketQuit();
    }

    void OnDestroy()
    {
        SocketQuit();
    }

    // 终止线程,关闭client
    void SocketQuit() 
    {
        thread.Abort();
        thread.Interrupt();
        client.Close();
    }

}

现在可以使用socket调试软件连接9000端口,发送 W A S D 即可控制方块前后左右移动。

参考:

unity UDP 发送与接收

posted @ 2022-07-26 10:27  姜小豆  阅读(2362)  评论(0编辑  收藏  举报