Calling a web-service from a Unity3D scene

本文介绍如何从Unity3D游戏引擎中调用Web服务并解析返回的JSON数据,实现动态创建游戏对象。

As mentioned in the last post, today we’re going to have some fun pulling data fromour recently-implemented, cloud-based web-service into the Unity3D game engine.

My intention, here, is to reinforce the fact that exposing web-service APIs really does give you broader reach with your technology. In this case, we’ll be calling our web-service – implemented using F#, which we could not have included in our Unity3D project – inside a game engine that could be hosted on any one of a wide variety of operating systems.

A few words on Unity3D: according to its web-site, Unity3D is “a feature rich, fully integrated development engine for the creation of interactive 3D content.” While the main goal behind Unity3D (which from here on I’ll just call Unity) is clearly for people writing games, Unity is also a great visualization environment.

This technology is cool. It makes heavy use of .NET – perhaps not the first environment you’d think of when implementing a cross-platform game engine – but its use of Mono allows you to use it to create games for Windows, Mac, the web, Android, iOS, PS3, Wii and Xbox 360. Woah!

One of the great things about Unity is the sample content available for it. The default scene when you install Unity is called Angry Bots, for instance, which is a fully-featured third person shooter. Now I’m not actually interested in implementing a game for this post – although that might be pretty cool, shooting each of the spheres in an Apollonian packing ;-) – so I decided to start with a more architectural sample scene.

I didn’t want to make any static changes to the scene – it looks really cool as it stands – I just wanted to access the web-service, pull down the sphere definitions and then create “game objects” inside the scene dynamically at run-time.

A quick aside regarding my OS choice for this… I originally started working with the Windows version of Unity inside a Parallels VM on my Mac, but then decided to switch across to the Mac version of Unity. The scene loaded as well there as it did on Windows – nothing needed to change, at all. I installed the free version of Unity – which means I can’t build for mobile platforms or game consoles – but you can apparently get free trials of a version that builds for those environments, if so inclined.

Unity’s scripting environment is pretty familiar: the MonoDevelop editor installed with Unity is pretty decent – it was my first time using the tool, and I thought I’d give it a try rather than configuring Unity to use Visual Studio – and is well integrated with the Unity scene development environment. You can code in either Javascript or C# (no prizes for guessing which one I chose ;-), and it’s possible to have both in a scene.

I started off bringing down a JSON-reading implementation for their Wiki (be sure to add the Nullable class definition, listed further down the page) which would help me from my own code. I added an additional C# source file – which must be calledImportSpheres.cs, as it needs to match the name of the class – and placed this code in it:

using UnityEngine;

using System.Collections;

using System.Net;

using System.IO;

 

public class ImportSpheres : MonoBehaviour

{

  // The radius of our outer sphere

 

  const float radius = 0.8f;

 

  IEnumerator DownloadSpheres()

  {

    // Pull down the JSON from our web-service

 

    WWW w = new WWW(

      "http://apollonian.cloudapp.net/api/spheres/" +

      radius.ToString() + "/7"

    );

    yield return w;

 

    print("Waiting for sphere definitions\n");

 

    // Add a wait to make sure we have the definitions

 

    yield return new WaitForSeconds(1f);

 

    print("Received sphere definitions\n");

 

    // Extract the spheres from our JSON results

 

    ExtractSpheres(w.text);

  }

 

  void Start ()

  {

    print("Started sphere import...\n");

 

    StartCoroutine(DownloadSpheres());

  }

 

  void ExtractSpheres(string json)

  {

    // Create a JSON object from the text stream

 

    JSONObject jo = new JSONObject(json);

 

    // Our outer object is an array

 

    if (jo.type != JSONObject.Type.ARRAY)

      return;

 

    // Set up some constant offsets for our geometry

 

    const float xoff = 1, yoff = 1, zoff = 1;

 

    // And some counters to measure our import/filtering

 

    int displayed = 0, filtered = 0;

 

    // Go through the list of objects in our array

 

    foreach(JSONObject item in jo.list)

    {

      // For each sphere object...

 

      if (item.type == JSONObject.Type.OBJECT)

      {

        // Gather center coordinates, radius and level

 

        float x = 0, y = 0, z = 0, r = 0;

        int level = 0;

 

        for(int i = 0; i < item.list.Count; i++)

        {

          // First we get the value, then switch

          // based on the key

 

          var val = (JSONObject)item.list[i];

          switch ((string)item.keys[i])

          {

          case "X":

            x = (float)val.n;

            break;

          case "Y":

            y = (float)val.n;

            break;

          case "Z":

            z = (float)val.n;

            break;

          case "R":

            r = (float)val.n;

            break;

          case "L":

            level = (int)val.n;

            break;

          }

        }

 

        // Create a vector from our center point, to see

        // whether it's radius comes near the edge of the

        // outer sphere (if not, filter it, as it's

        // probably occluded)

 

        Vector3 v = new Vector3(x, y, z);

        if ((Vector3.Magnitude(v) + r) > radius * 0.99)

        {

          // We're going to display this sphere

 

          displayed++;

 

          // Create a corresponding "game object" and

          // transform it

 

          var sphere =

            GameObject.CreatePrimitive(PrimitiveType.Sphere);

          sphere.transform.position =

            new Vector3(x + xoff, y + yoff, z + zoff);

          float d = 2 * r;

          sphere.transform.localScale =

            new Vector3(d, d, d);

 

          // Set the object's color based on its level

 

          UnityEngine.Color col = UnityEngine.Color.white;

          switch (level)

          {

          case 1:

            col = UnityEngine.Color.red;

            break;

          case 2:

            col = UnityEngine.Color.yellow;

            break;

          case 3:

            col = UnityEngine.Color.green;

            break;

          case 4:

            col = UnityEngine.Color.cyan;

            break;

          case 5:

            col = UnityEngine.Color.magenta;

            break;

          case 6:

            col = UnityEngine.Color.blue;

            break;

          case 7:

           col = UnityEngine.Color.grey;

           break;

          }

          sphere.renderer.material.color = col;

        }

        else

        {

          // We have filtered a sphere - add to the count

 

          filtered++;

        }

      }

    }

 

    // Report the number of imported vs. filtered spheres

 

    print(

      "Displayed " + displayed.ToString () +

      " spheres, filtered " + filtered.ToString() +

      " others."

    );

  }

 

  void Update ()

  {

  }

}

There’s nothing earth-shattering about this code: it calls our web-service to pull down a fairly detailed (level 7) representation of an Apollonian packing and inserts the resultant spheres into the current scene.

The code makes use of some Unity-specific classes, such as WWW – rather than some standard .NET capabilities which proved a bit more problematic – and there were some quirks needed to implement “co-routines” from C# (which meant having to return an IEnumerator and use yield return).

Being based on Mono, your Unity code is always going to be a bit behind the state-of-the-art in the latest .NET Framework, but hey – that’s the cost of being cross platform. :-)

Otherwise, it’s probably worth mentioning that the code only adds GameObjects for spheres that are close to the outside of the outer sphere, as they would only end up being occluded, anyway.

After the script has been added to the scene – in this case in the _Scripts folder – it’s a relatively simple matter of attaching it to one of the scene’s objects, to make sure it gets called. This step took me some time to work out – despite it being really simple, once you know how – so I’ll step through it, below.

From the base scene with our scripts added…Our initial scene with our two scripts added

We just need to select a game object (in this case I chose the computer desk, but we could select anything in the initial scene), and then choose Component –> Scripts –> Import Spheres.

Attaching our script to a game object

Our script attached to the object in the InspectorOnce this has been selected, we should be able to see the script attached to the selected object in the Inspector window on the right. This means the script will be executed as the game object – and as a static object this ultimately means the scene – loads.

The script will be checked, by default – to stop it from running you can either uncheck it or use the “cog” icon to edit the script settings and select “Remove Component” to get rid of it completely.

Now we can simply run the scene using the “play” icon at the top – which runs the scene inside the editor – or you can build it via the File menu and run the resultant output.

Here’s the scene in the editor:

Our Apollonian Apartment in action

I tried embedding the Unity web player in this post, directly, but gave up: it seems you need to edit the <head> section of your HTML page to load the appropriate script: I could do that for every post on this blog, but that seems like unnecessary overhead. If you’d like to give the scene a try, you’ll have to open a separate page to do so.

Once small note: I did need to add a crossdomain.xml file to our Azure-hosted ASP.NET web-service, to make sure it met with Unity’s security requirements.

Right – that’s it for today’s post. Next time we’ll be continuing to look at using our data in other places, as we shift gears and implement a basic 3D viewer for the Android platform.


原文 http://through-the-interface.typepad.com/through_the_interface/2012/04/calling-a-web-service-from-a-unity3d-scene.html


标题基于Python的汽车之家网站舆情分析系统研究AI更换标题第1章引言阐述汽车之家网站舆情分析的研究背景、意义、国内外研究现状、论文方法及创新点。1.1研究背景与意义说明汽车之家网站舆情分析对汽车行业及消费者的重要性。1.2国内外研究现状概述国内外在汽车舆情分析领域的研究进展与成果。1.3论文方法及创新点介绍本文采用的研究方法及相较于前人的创新之处。第2章相关理论总结和评述舆情分析、Python编程及网络爬虫相关理论。2.1舆情分析理论阐述舆情分析的基本概念、流程及关键技术。2.2Python编程基础介绍Python语言特点及其在数据分析中的应用。2.3网络爬虫技术说明网络爬虫的原理及在舆情数据收集中的应用。第3章系统设计详细描述基于Python的汽车之家网站舆情分析系统的设计方案。3.1系统架构设计给出系统的整体架构,包括数据收集、处理、分析及展示模块。3.2数据收集模块设计介绍如何利用网络爬虫技术收集汽车之家网站的舆情数据。3.3数据处理与分析模块设计阐述数据处理流程及舆情分析算法的选择与实现。第4章系统实现与测试介绍系统的实现过程及测试方法,确保系统稳定可靠。4.1系统实现环境列出系统实现所需的软件、硬件环境及开发工具。4.2系统实现过程详细描述系统各模块的实现步骤及代码实现细节。4.3系统测试方法介绍系统测试的方法、测试用例及测试结果分析。第5章研究结果与分析呈现系统运行结果,分析舆情数据,提出见解。5.1舆情数据可视化展示通过图表等形式展示舆情数据的分布、趋势等特征。5.2舆情分析结果解读对舆情分析结果进行解读,提出对汽车行业的见解。5.3对比方法分析将本系统与其他舆情分析系统进行对比,分析优劣。第6章结论与展望总结研究成果,提出未来研究方向。6.1研究结论概括本文的主要研究成果及对汽车之家网站舆情分析的贡献。6.2展望指出系统存在的不足及未来改进方向,展望舆情
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值