Sunday, February 26, 2017

Oculus Rift Unity3d Battle Game

BattleToys

BattleToys is a mini game (and tech demo) that uses the Oculus Rift and the Myo armband to fight evil sock animals in a twisted child's bedroom.
BattleToys is based on an existing game designed by Unity for tutorial purposes. The tutorial game, "Survival Shooter", is a game designed in 2014 to teach potential Unity users how to design games in the Unity engine. We adapted this game and added enhanced Oculus Rift support, added our own hammer weapon, and added the Myo armband support to control our weapon!

Download

You can find a pre-built release here:
https://github.com/alberthdev/battletoys/releases

Building

To build the game, download the source code here:
https://github.com/alberthdev/battletoys/archive/master.zip
Open the downloaded source code folder in Unity 5.x, and build it from there!

AR Vuforia Unity3d

ar-vuforia-unity-demo

Augmented Reality demo made with Vuforia and Unity 5.
I have used one of my books cover as target image to show a 3D model.
See the demo here: https://vimeo.com/164908588
gif

Images

Image target
http://imgur.com/R0LuWyV.png
Screenshots
png png

Vuforia with OpenCV for Unity Example

Vuforia with OpenCV for Unity Example

Demo Video


Environment

Windows 8.1
Unity 5.5.1f1
vuforia-unity-6-2-6.unitypackage
SD_UnityChan-1.unitypackage
OpenCV for Unity 2.1.3
In Unity 4.6, It seems the black screen problem occurs while using the combination of Vuforia and OpenCVForUnity. I am investigating the cause.Unfortunately, please use the Unity5 at the moment.

Setup

  • Import vuforia-unity-6-2-6.unitypackage
  • Import SD_UnityChan-1.unitypackage
  • Setup Vuforia (How To Setup a Simple Unity Project)
  • Import OpenCVForUnity2.1.3 from AssetStore
  • Import VuforiaWithOpenCVForUnityExample.unitypackage
screenshot.png

Examples

CameraImageToMatExample.cs
Conversion from CameraImage(without augmentation) of "Vuforia" to Mat of "OpenCV for Unity".
PostRenderToMatExample.cs
Conversion from PostRenderTexture(ARCamera) of "Vuforia" to Mat of "OpenCV for Unity".
Attach "PostRenderToMatExample.cs" to "ARCamera/Camera".
Light_Frame.png

Unity3d Mecanim Effects


MecanimEffects

Bind visual effects to Mecanim (Unity 3D animation system) states in the editor.

What is effect

We define effect here as a GameObject prefab. It can contain animated textures, particle emitters, audio sources, anything you want. Follow next few steps to create a sample effect.
  1. Create an empty GameObject with Game Object > Create empty menu command.
  2. In the Inspector window click Add Component button and select Effects > Particle system.
  3. Drag that game object from Hierarchy to Project window to create a new prefab.
  4. That's it!

Using effects with Unity Editor

To try out mecanim effects you'll need a scene with any object animated with mecanim. Open that scene in Unity Editor and prepare the sample effect like the one defined before.
  1. In scene view select any object animated with Mecanim. It must have Animator component attached and a state machine with two or more states.
  2. In the Inspector window click Add Component button and select EffectsController.
  3. In the EffectsController inspector select animator, add one binding to the Bindings list, and expand it.
  4. In the Binding inspector set State Name property to any of existing states by typing "." without quotes.
  5. Expand the Effects property and add 1 (one) effect and expand it.
  6. In the Effect inspector set the Prefab property to previously created sample effect prefab.
  7. Done!
Now you can run the scene and see effect appears when object goes into selected state and disappears when state is changing.

Additional editor features

  • By default effects appears as transform children of the object EffectsController is attached to. You can change this behavior by setting the Subject property in the Effect inspector.
  • You can use Animator component from any GameObject in the scene.
  • Use Reset On Replay flag in the Effect inspector to send Reset message to effect every time it is played.

Scripting effects

Mecanim Effects utilizes Unity 3D messaging system to introduce the custom scripting feature. Also state information and timer values are precalculated every frame and can be used in your scripts.

Messages

EffectsController can send three types of messages to the game object it is attached to.
  • Enter Message is sent in Update cycle in the first frame of the selected animator state;
  • Update Message is sent in Update cycle every frame the selected animator state remains active;
  • Timer Message is sent in Update cycle when timer reaches the timer treshold and only if timer treshold is more than zero;
  • Exit Message is sent in Update cycle in the frame following the last frame of the selected animator state.
Messages are sent only if name is explicitly specified in the Inspector window. When appopriate field is blank no message is sent to the object. Messages are sent using SendMessageOptions.RequireReceiver option value, so there will be a warning about unhandled messages.
At the moment an update message is sent along with enter message in the same update cycle. However this behavior is under question and may be changed in the future.
Example of message handler in C#:
void OnBaseLayerMoveEnter(EffectUpdateEventArgs e) {
   // your logic here
}

Timers and states

Current state and transition information is provided with EffectUpdateEventArgs class instace. Here is the EffectUpdateEventArgs class definition:
public class EffectUpdateEventArgs : System.EventArgs {
  public EffectsController controller;
  public int layerIndex;
}
Using controller.layerState array along with layerIndex value you can query and manipulate the handled animator's state or transition information. EffectUpdateEventArgs instance is sent along with every message.
Timings are essential for building game effects and animations. MecanimEffects provides you with Timer Message and the animator state timer values are calculated each Update call. You can use them within your messsage handlers. MecanimEffects provides following values:
  1. State seconds - state time in seconds from the beginning of current iteration.
  2. State seconds total - state time in seconds from the beginning of the first iteration.
  3. Loop count - state iteration count.
Example of getting a value:
void OnMyStateUpdate(EffectUpdateEventArgs e) {
   var stateSeconds = e.controller.layerState[e.layerIndex].stateSeconds;
}
You are not expected to store the reference to the instance of EffectUpdateEventArgs between calls or change its fields values. You are not expected to use layerState array outside of EffectController's message hadlers. This is because Unity 3D does not determine the order of calling Update on GameObject and therefore you can accidentaly get data from previous frame or uninitialized references in the first frame.

License

WTFPL – Do What the Fuck You Want to Public License
See license.txt for full license text.

Roadmap

  • Custom inspector UI - default inspector looks creepy and unintuintive, a new cool Inspector UI is coming soon!
  • Cross-state effects caching - states with same effect bound can share cachedInstance.
  • Continious effects - effects do not disappear in transition if the next state have similar effect attached. This is possible only with cross-state caching.

Planet Unity sample for doing an image search and putting the results in a PUGridTable

Image Search Example

Built with Planet Unity

This is a moderate example of how to build Unity UI using Planet Unity; it creates an application which allows you to perform an image by entering some text in an input field, pressing the search button, performing some asynchronous web requests and populating a grid table with the resulting images.
kittens!

Reconstructing from scratch

While having access to the completed project is nice, it can be much more informative to build it yourself from scratch. Here are the step-by-step instructions on how to duplicate this project on your own:

Creating and preparing the Unity project

  • Open Unity and create a new project
  • Create a Assets/Resources/Search folder
  • Create a Assets/Code folder
  • Create a Assets/Scenes folder
  • Create a new scene and save it as Assets/Scenes/Search.unity
  • Follow the Planet Unity integration instructions. I git-submoduled PlanetUnity to Assets/PlanetUnity2

Creating the basic UI of the Search scene

  • Create a new XML file Assets/Resources/Search/Search.xml
  • Add the following XML to Search.xml. This will provide a basic Canvas and a white square set to cover the entire screen.
      <?xml version="1.0" encoding="utf-8" ?>
      <Canvas renderMode="ScreenSpaceCamera" xmlns="http://schema.smallplanet.com/PlanetUnity2.xsd" >
          <Color color="#FFFFFFFF" anchor="stretch,stretch" />
      </Canvas>
    
  • In the Search.unity scene, you should have created a Game Object and attached the Planet Unity Game Object component to it. In the XmlPath field, add the path "Search/Search" (that's the Assets/Resources/Search/Search.xml path)
  • At this point, you should be able to play the Unity Editor and see the canvas and white square in the object hierarchy.

Creating a class to provide project specific overrides to Planet Unity

  • Planet Unity provides a lot of overrides and customizations to help fit your project needs. For this project, we need to override the default image loading optimization to allow Planet Unity to load Sprites.
  • Create a new C# script in Assets/Code/PlanetUnityOverrides.cs, add the following code to the file:
      using UnityEngine;
      public class PlanetUnityOverrides : MonoBehaviour, IPUCode {
    
          public void Awake() {
              PlanetUnityOverride.ForceActualSprites = true;
          }
      }
    
  • When setting overrides, it is important to set them in the Awake method. The Planet Unity Game Object component will load everything in the Start method, so this will ensure your overrides are properly set before any of the UI is loaded.
  • Add this new component to your the game object which contains your the Planet Unity Game Object component (technically it can be on any game object).

Creating the search field and search button

  • Add the following images ( searchButton.png, searchIcon.png, and inputFieldBackground.png ) to the Assets/Resources/Search folder
  • For the searchButton.png and the inputFieldBackground.png we want them to be Sprites and their border values set to 31,31,31,31 (this will allow them nicely to 9-point stretch to fill the space)
  • In Search.xml, add the the input field after the background color:
      <!-- This is a gray bar going along the top of the screen ; this will eventually cover the grid of images when they scroll up under the input field -->
      <Color color="#DDDDDDFF" bounds="@eval(0,0,w,68)" pivot="0,1" anchor="top,stretch" />
      <!-- This is the background images for the input field -->
      <Image resourcePath="Search/inputFieldBackground" bounds="10,-10,700,48" pivot="0,1" anchor="top,stretch">
          <!-- This is the actual input field component -->
          <InputField title="SearchField" onValueChanged="PerformSearch" sizeToFit="true" maxFontSize="28" alignment="middleLeft" bounds="@eval(10,10,w-20,h-20)" anchor="stretch,stretch" />
          <!-- This is the blue search button, attached to the right side of the text field -->
          <ImageButton resourcePath="Search/searchButton" onTouchUp="PerformSearch" bounds="@eval(0,0,48,48)" pivot="0,0.5" anchor="middle,right">
              <Image resourcePath="Search/searchIcon" pivot="0.5,0.5" bounds="@eval(0,0,w-20,h-20)" anchor="middle,center" />
          </ImageButton>
      </Image>
    
  • At this point, you should be able to Play the editor and see the gray bar along the top, the input field, and the blue search button

Adding the grid table and the controller class

  • When the results of the image search requests comes in, we will place those results in a nice scrolling table for the user to browse through. Add the following to Search.xml, right above the gray bar entity.
    <GridTable title="ImageResultsTable" expandToFill="false" bounds="@eval(0,0,w,h-68)" anchor="stretch,stretch" />
    
  • Before we write a C# script to control this scene, we want to attach it to this scene using a Code entity. Add the following lines to the bottom of Search.xml. When Planet Unity loads the XML, it will create an instance of the SearchController class, and link any titled entities to that classes member variables.
      <Code class="SearchController">
          <Notification name="PerformSearch" />
      </Code>
    
  • Now that the grid table and the input field is in place, we need to write some controller code to take the input from the text field, run the image search, and output the resulting images into the grid table. Create a C# script file at Assets/Code/SearchController.cs and put the following script into it:
    SearchController.cs
  • The public member variables which match the names and types of the titled entities will be populated automatically on creation of the controller class instance.
  • This code relies on litjson for the JSON parsing; you should include litjson or another JSON parser to handle this.
  • This is a standard Unity MonoBehaviour subclass, and it added as a comoponent to the game object which gets created by the Code entity
  • When you end editing on the input field, or press the search button, a code notification is sent named PerformSearch. In the previous step in our Code entity we have a Notification entity, whose name is PerformSearch. This tells the code entity that it should listen for notifications of PerformSearch and when they happen, call the PerformSearch() method on the SearchController class.

Code to support using PUTables

  • To use any variant of PUTable (PUTable, PUGridTable, or PUSimpleTable) we need to do a little bit more work; we need to create table cell classes for each type of table cell class we want to the table to be able to hold
  • These classes, along with some image downloading code which uses Unity's WWW class and coroutine to download the images asynchronously, are in the ImageTableSupport.cs
    ImageTableSupport.cs
  • To use PUTable, you supply a list of objects ( List<object>() ) to the entity by calling SetObjectList().
  • The list should be a list of data classes which contain the data for each cell (in our example, the ImageResult class )
  • We need to create a subclass of PUTableCell named the same name as our data class + TableCell (in our example ImageResultTableCell). This class is responsible to creating the view of each cell (either programmatically or by loading a table cell XML file), and being the controller for this cell (putting the actual data for each cell in the cell's views).

All done

At this point you should be able to play the Unity Editor, enter a search text in the input field, press the search button, and see the image search results populate the grid table.

License

PlanetUnity is free software distributed under the terms of the MIT license, reproduced below. PlanetUnity may be used for any purpose, including commercial purposes, at absolutely no cost. No paperwork, no royalties, no GNU-like "copyleft" restrictions. Just download and enjoy.
Copyright (c) 2014 Small Planet Digital, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

About Small Planet

Small Planet is a mobile agency in Brooklyn, NY that creates lovely experiences for smartphones and tablets. PlanetUnity has made our lives a lot easier and we hope it does the same for you. You can find us at www.smallplanet.com.

ETS2-Data-Viewer-Unity

ETS2-Data-Viewer-Unity

A simple software to connect the the ETS2 Telemetry Server, and view data such as Cargo, Distance to delivery, ETA (in game time) and estimated Real Time ETA (based on the calculated game Time Scale). It also displays the speed limit and you can toggle between NOK support (Norwegian currency) for ETS2 Scandinavian DLC support.
It runs on 10 fps, as not more is needed for a nice steady update of information. It connects to @Funbit's Telemetry Server and fetches the JSON and parses it with NewtonSoft.
Screenshot:
Imgur

Unity RTS Game

Unity RTS Game

Unity Real Time Strategy Game following the tutorial:
Noobtuts - RTS

Prerequires

  1. Unity 5.3+

Game


References

  1. Noobtuts - RTS