Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/318.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何通过HTML5上的信号器向Unity3D游戏发送数据?_C#_Asp.net_Html_Unity3d_Signalr - Fatal编程技术网

C# 如何通过HTML5上的信号器向Unity3D游戏发送数据?

C# 如何通过HTML5上的信号器向Unity3D游戏发送数据?,c#,asp.net,html,unity3d,signalr,C#,Asp.net,Html,Unity3d,Signalr,我遵循了德国博客上的教程 之后,我创建了一个脚本,当在屏幕上单击时,它会输出HTML5手的坐标。我想使用提供的服务器和客户端将这些坐标发送到Unity游戏 虽然我不会继续讨论这个特定的示例,但我将使用SignalR查看其他示例,并采纳其他网络建议,以允许unity和webplayer建立连接 统一代码:(发送数据) playerController.cs(1/2) 现在,解决方案部分: 我必须添加另一个信号中心吗 我是否应该将“仍然使用广播”更改为“全部” 我要为UNity更改哪个文件?我应该创

我遵循了德国博客上的教程

之后,我创建了一个脚本,当在屏幕上单击时,它会输出HTML5手的坐标。我想使用提供的服务器和客户端将这些坐标发送到Unity游戏

虽然我不会继续讨论这个特定的示例,但我将使用SignalR查看其他示例,并采纳其他网络建议,以允许unity和webplayer建立连接

统一代码:(发送数据) playerController.cs(1/2)

现在,解决方案部分:

  • 我必须添加另一个信号中心吗
  • 我是否应该将“仍然使用广播”更改为“全部”
  • 我要为UNity更改哪个文件?我应该创建另一个名为Listener.cs的.cs文件吗
  • 为了使HTML5索引正确,我应该更改哪个文件
  • 函数(接收)的名称是什么
  • 解决方案是可扩展的还是补丁

  • 有消息吗?你能做到吗?信号器工作得很好,但是让它与多点触控一起工作有太多的参数,我使用python Webstream切换到TUIO,使用IDEA Pycharm和Java在本地连接到Java TUIO应用程序
    using UnityEngine; 
    
    public class Playercontrollers : MonoBehaviour { 
    
        public Camera cam; 
        private float maxWidth; 
        private float maxHeight; 
    
        bool isHandOpen = true; 
        public Sprite clickedSprite; 
        private Sprite standardSprite; 
    
        private SignalRUnityController _signalr; 
    
        void Start() 
        { 
            if (cam == null) 
                cam = Camera.main;
    
           _signalr = GameObject.Find("SignalRObject").GetComponent<SignalRUnityController>();
    
            var corner = new Vector3(Screen.width, Screen.height, 0f); 
            var targetWidth = cam.ScreenToWorldPoint(corner); 
            float playerWidth = GetComponent<Renderer>().bounds.extents.x; 
            float playerHeight = GetComponent<Renderer>().bounds.extents.y; 
            maxWidth = targetWidth.x - playerWidth; 
            maxHeight = targetWidth.y - playerHeight; 
    
            standardSprite = this.GetComponent<SpriteRenderer>().sprite; 
    
        } 
        void FixedUpdate() 
        { 
            var currentPosition = cam.ScreenToWorldPoint(Input.mousePosition); 
            float targetWidth = Mathf.Clamp(currentPosition.x, -maxWidth, maxWidth); 
            float targetHeight = Mathf.Clamp(currentPosition.y, -maxHeight, maxHeight); 
            var newPosition = new Vector3(targetWidth, targetHeight, 0f); 
            GetComponent<Rigidbody2D>().MovePosition(newPosition); 
    
            if (Input.GetMouseButtonDown(0)) 
            { 
                isHandOpen = false; 
                MouseDown(); 
            } 
            else if(Input.GetMouseButtonUp(0)) 
            { 
                isHandOpen = true; 
                MouseUp(); 
            } 
    
            var worldCoordinates = cam.WorldToScreenPoint(newPosition);
            var json = "{"+string.Format("\"x\": \"{0}\", \"y\": \"{1}\", \"handOpen\": \"{2}\"", worldCoordinates.x, worldCoordinates.y, isHandOpen) +"}";
            //var json = "{\"x:791, y:10,handOpen: True\"}";
            Debug.Log(json);
            _signalr.Send("Position", json); 
    
        } 
    
        private void MouseDown() 
        { 
            Debug.Log("MouseDown"); 
            this.GetComponent<SpriteRenderer>().sprite = clickedSprite; 
    
        } 
    
        private void MouseUp() 
        { 
            Debug.Log("MouseUp"); 
            this.GetComponent<SpriteRenderer>().sprite = standardSprite; 
        } 
        public static void Receive()
        {
            Debug.Log("Change position from controller");
            //var newPosition = new Vector3(450, 175, 0f);
            //GetComponent<Rigidbody2D>().MovePosition(newPosition);
    
        }
    
    } 
    
    using SignalR.Client._20.Hubs;
    using UnityEngine;
    using System.Collections;
    
    public class SignalRUnityController : MonoBehaviour {
    
        public bool useSignalR = true;
        public string signalRUrl = "http://localhost:50283/";
    
        private HubConnection _hubConnection = null;
        private IHubProxy _hubProxy;
        private IHubProxy _hubProxyReceive;
        private Subscription _subscription;
        public Playercontrollers player;
    
    
    
        //start connection to the outer web page
        void Start () {
    
            if (useSignalR)
                StartSignalR();
        }
    
        void StartSignalR()
        {
            if (_hubConnection == null)
            {
                _hubConnection = new HubConnection(signalRUrl);
    
                _hubProxy = _hubConnection.CreateProxy("signalRHub");
                _subscription = _hubProxy.Subscribe("broadcastMessage");
                _subscription.Data += AudioDataLoadState =>
                {
                    Debug.Log("signalR called us back");
                    Playercontrollers.Receive();
    
                };
                _hubConnection.Start();
    
            }
            else
                Debug.Log("SignalR already connected...");
        }
    
    
        /// <summary>
        /// Send single message of direction over broadcast
        /// </summary>
        // Update is called once per frame
        public void Send(string method, string message){
            if (!useSignalR)
                return;
    
            var json = "{" + string.Format("\"action\": \"{0}\", \"value\": {1}", method, message) + "}";
            _hubProxy.Invoke("Send", "UnityClient", json);
    
        }
        public void Receive(string method, string message)
        {
           // if (!useSignalR)
              //  return;
    
            //_hubProxyReceive.Subscribe("Receive", "UnityClient");
    
        }
    
    }
    
    <!DOCTYPE html>
    
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title> Unity to webPlayer Sample </title>
    
        <Style> 
          body {
            background: url(images/game-background.png);
            /*background-size54321:*/
            background-repeat: no-repeat;
          }
    
          #player {
    
            position: absolute;
    
            top: 30px;
    
            left: 30px;
    
          }
          #contentContainer {
        width: 500px;
        height: 500px;
        border: 5px black solid;
        overflow: hidden;
        background-color: none;
        cursor: pointer;
    }
    
          </Style>
    
    </head>
    
    
    <body>
        <div id="contentContainer">
            <img id="player" src="images/OpenHand.png" />
            </div>
    
    
            <div id="infoContainer">
    
                <label id="message"></label>
    
            </div>       
            <div id="transportContainer">
    
                <label id="connected"></label>
    
            </div>
    
            <!---Script references. -->
            <!--Reference the jQuery Library54321. -->
    
            <script src="Scripts/jquery-1.6.4.min.js"></script>
    
            <!--Reference the SignalR library54321. -->
    
            <script src="Scripts/jquery.signalR-2.1.1.min.js"></script>
    
            <!--Reference the autogenerated SignalR hub script. -->
    
            <script src="signalr/hubs"></script>
    
            <!--Add script to update the page and receive messages.-->
        <script src="//www.kirupa.com/prefixfree.min.js"></script>
            <script type="text/javascript">
                var theThing = document.querySelector("#player");
                var container = document.querySelector("#contentContainer");
    
                container.addEventListener("click", getClickPosition, false);
    
                function getClickPosition(e) {
                    var parentPosition = getPosition(e.currentTarget);
                    var xPosition = e.clientX - parentPosition.x - (theThing.clientWidth / 2);
                    var yPosition = e.clientY - parentPosition.y - (theThing.clientHeight / 2);
    
                    theThing.style.left = xPosition + "px";
                    theThing.style.top = yPosition + "px";
                    console.log(xPosition + " " + yPosition);
                }
    
                // Helper function to get an element's exact position
                function getPosition(el) {
                    var xPos = 0;
                    var yPos = 0;
    
                    while (el) {
                        if (el.tagName == "BODY") {
                            // deal with browser quirks with body/window/document and page scroll
                            var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
                            var yScroll = el.scrollTop || document.documentElement.scrollTop;
    
                            xPos += (el.offsetLeft - xScroll + el.clientLeft);
                            yPos += (el.offsetTop - yScroll + el.clientTop);
                        } else {
                            // for all other non-BODY elements
                            xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
                            yPos += (el.offsetTop - el.scrollTop + el.clientTop);
                        }
    
                        el = el.offsetParent;
                    }
                    return {
                        x: xPos,
                        y: yPos
                    };
                }
                $(function () {
                    var hub = $.connection.SignalRHub;
                    var echo = $.connection.echo;
    
                    echo.client.greetings = function (message) {
                        $('#message').html(message);
    
                    };
    
                    var started = hub.start();
    
                    started.done(function () {
                        echo.server.say("hello! New User 5671 joined");
                    });
    
                });
    
                $(function () {
                    //$('#message').text('connected');
    
                    //  Declare a proxy to reference the hub.
    
                    var signalrHub = $.connection.signalRHub;
    
    
    
    
    
                    //Create a function that the hub can call to broadcast messages.
    
                    signalrHub.client.broadcastMessage = function (name, message) {
                        console.log(message);
                        var messageobj = JSON.parse(message);
    
    
    
                        if (messageobj.action == 'Position') {
                            console.log("Position + Position");
    
                            $('#player').css('left', messageobj.value.x + 'px');// update the x value
                            $('#player').css('top', 500 - $('#message').height() - messageobj.value.y + 'px');// update the x value
                            $('#message').text('x:' + messageobj.value.x + "px, y:" + messageobj.value.y + 'px');
                            if (messageobj.value.handOpen == 'True')
                                $('#player').attr('src', 'Images/OpenHand.png');
                            else
                                $('#player').attr('src', 'Images/ClosedHand.png');
                        }
                    };
    
                    var started = signalrHub.start({
                        transport: [
                        'webSockets',
                        'longPolling',
                        'serverSentEvents',
                        'foreverFrame'
                        ]
    
                    });
    
                    //start the connection to the server to display on the webpage
                    $.connection.hub.start().done(function () {
                        $('#message').text('connected');
                        $('#connected').text('connected, transport: ' + signalrHub.transport.name);
                        console.log('connected, transport: ' + signalrHub.transport.name)
                    });
    
    
                    $.connection.hub.start().done(function () {
                        $('#contentContainer').click(function () {
                            console.log("Clicked");
                            //Call the Send method on the hub. 
                            //chat.server.send($('#displayname').val(), $('#message').val());
                            // Clear text box and reset focus for next comment. 
                            //$('#message').val('').focus();
                        });
                    });
    
                });
    
            </script>
    
    
    </body>
    </html>
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Hubs;            //include this to add hub names ["echo"]
    
    namespace SignalRUnityWeb
    
    {
        /// <summary name="SignalRHub">Name of the c# file</summary>
        [HubName("hub") ]
        public class signalRHub : Hub
        {
            /// <summary>
            /// The purpose of receive if for the Unity to have a function called receive that receives data from the web page
            /// </summary>    
            /// <param name="name">name of the connection</param>
            /// <param name="message">single message to be sent through network</param>
            public void Send(string name, string message)
            {
                //Call the broadcastMessage method to update the clients.
    
                Clients.All.broadcastMessage(name, message);
            }
        }
    }
    
    using System;
    using System.Threading.Tasks;
    using Microsoft.Owin;
    using Owin;
    
    [assembly: OwinStartup(typeof(SignalRUnityWeb.Startup))]
    
    namespace SignalRUnityWeb
    {
        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
                app.MapSignalR();
            }
        }
    }