Search Unity

Use UDP message to transform object

Discussion in 'Getting Started' started by simonapernisch, Dec 23, 2019.

  1. simonapernisch

    simonapernisch

    Joined:
    Dec 12, 2019
    Posts:
    2
    Hi I am very new to Unity and can't figure out this issue

    I got a matlab script creating a sinus signal
    With UDP i connect Unity with Matlab. Now the code works, but it is showing me the numbers only after I end the streaming from Matlab, but I want it to be "live". So not read the message untill the end but read it as it comes. But i cannot make it work with "read" instead of "readtoend".

    Second problem: how do i use the message from UDP to then move an object? I somehow need to convert the message into int?

    Here is the matlab code:
    function udpStreamer()
    global KEY_IS_PRESSED
    KEY_IS_PRESSED = 0;
    gcf;
    text(0.15, 0.5, {'Press any key while this window is in focus to' 'terminate the udp stream on port 55001'}, 'interpreter', 'none')
    text(0.15, 0.3, {'Packets should arrive at ~100Hz as a string:' ' ''Stream1currentValue_Stream2currentValue'''}, 'interpreter', 'none')
    set(gcf, 'KeyPressFcn', @terminationDetector)

    %start upd server at (adress, port)
    uu = tcpip('127.0.0.1',55001,'NetworkRole','Client');
    set(uu,'Timeout',30);
    fopen(uu);
    disp('Transmission on 127.0.0.1:55001 initiated')

    while ~KEY_IS_PRESSED
    drawnow
    % start transmitting a datastream
    for x= 0:0.1:1 %2*pi %loop writes 62 values per iteration at about 100Hz with some fake stuttering
    packet = [num2str(sin(x)) '_' num2str(cos(x))];
    fwrite(uu, packet)
    pause(0.0545)
    end
    end
    %close the udp server
    fclose (uu);
    close
    disp('Transmission on 127.0.0.1:55001 terminated')


    function terminationDetector(hObject, event)
    global KEY_IS_PRESSED
    KEY_IS_PRESSED = 1;
    disp('Termination wish detected')

    Here is my script
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    using System.Net;
    using System.Net.Sockets;
    using System.Linq;
    using System;
    using System.IO;
    using System.Text;
    public class UDPReceiver : MonoBehaviour
    {
    // Use this for initialization
    TcpListener listener;
    String msg;


    void Start()
    {
    listener = new TcpListener(IPAddress.Any, 55001);
    listener.Start();
    print("is listening");
    }
    // Update is called once per frame
    void Update()
    {
    if (!listener.Pending())
    {
    }
    else
    {
    print("socket comes");
    TcpClient client = listener.AcceptTcpClient();
    NetworkStream ns = client.GetStream();
    StreamReader reader = new StreamReader(ns);
    msg = reader.ReadLine();
    print(msg);



    }

    //transform.Translate(0, 0.01f, 0);
    //print("Object is moving");

    }
    }
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,448