text:
tag:gamedevelopment.tutsplus.com,2005:/categories/unity-3d Envato Tuts+ Game Development - Unity 3D 2018-05-14T12:30:15Z tag:gamedevelopment.tutsplus.com,2005:PostPresenter/cms-30437 Creating a Unity Game With PlayMaker

What You'll Be Creating

In this article, I will show you how to make a game object move in five minutes or less using the PlayMaker add-on for Unity, with no code.

Download Unity

If you haven't already, head over to the Unity website and download the latest version of Unity. Unity is a free, user-friendly game engine that allows developers and studios to create 3D games for Android, iOS, Windows, and over 20 other platforms.

About PlayMaker

What exactly is PlayMaker? PlayMaker is a paid add-on for Unity that allows you to create games without having to code. Created by Hutong Games, PlayMaker uses functional state machines (FSM) to add physics, animation, interactive objects and scene changes easily. Their developers have already created the scripts for you, which can significantly cut your game development time in half. As of writing this tutorial, the current price is $65.00, with over 370 five-star reviews.

Downloading PlayMaker

Once you have Unity, create a new 3D project. I made a simple scene with a terrain and a sphere. In the main viewport, under the menu toolbar, you will find the Asset Store tab. Type PlayMaker into your search box. Follow the instructions to place your purchase. You may need to use the link in your confirmation email or import it directly through Unity. You may find that it takes you back to the asset store, but don't worry—click Add to Cart and it should give you the download option.

Download the file and unzip it into a folder you can easily find. Now let's import a custom package by going to Assets > Custom Package and opening your unzipped PlayMaker file.

After you've imported the package, choose Install PlayMaker. This will add the PlayMaker option in your menu bar.

Game Objects

Every FSM needs to be attached to an object. In this case, our sphere will be the object we are looking to control. Later, we will need to specify our game object once an action is created. For now, let's confirm our sphere has a rigid body. In addition, let's freeze the X and Y position of our sphere in the Inspector window.

The PlayMaker Editor

Go to the PlayMaker tab on your top menu bar and click PlayMaker editor. This will open the below window. Click and drag the tab to place it next to your Game tab on the bottom.

On the right of the editor window, you will see four tabs:

FSM

State

Events

Variables

This is where you will choose the options and parameters for your state. Along with changing the name, you can add in your own description, which comes in handy when you have large projects. For example, this state will move the ball left.

To add a state machine to an object, choose your object in the Hierarchy. Head over to the Editor window and right click to add an FSM. This begins the state machine, and this will be state one.

Second, we need to create a System Event (what happens after user interaction). This is what will set off the state, for example button clicked or mouse over. For this project, we will choose mouse over.

Let's create our next state and name it Ball Moves. You will immediately see a red exclamation point; this is because once you create a state, you will have to define a transition. To define a transition from one state to the other, right-click and choose Transition Target. There you will see the name of the second state you created. You will now see an arrow connecting your two states.

It's time to add physics to our object. The way we do this is by activating the Action Browser. There are numerous actions you can choose for your object, which is pretty cool.

Feel free to look around at all of the commands you can use in your project. For every action, we will need to set up parameters.

Adding Movement

In order to make our sphere move, we will need to give it force and velocity through the Action Browser. First, make sure the proper state is chosen. To search for an action, type it in the search box. Let's search for add force. Under the State tab to the right, change the Y variable to 100.

Now let's add velocity by repeating the steps above. Change the Y variable to 50.

Hit play and voila! Your sphere should move towards the camera. There are almost an unlimited amount of actions you can perform simply with PlayMaker once you understand the interface.

Conclusion

In my opinion, PlayMaker is a great addition to Unity. Even if you do have coding experience, it can make it that much easier to create interactive, fully animated games in half the time.

Unity has an active economy. There are many other products that help you build out your project. The nature of the platform also makes it a great option from which you can better your skills. Whatever the case, you can see what we have available in the Envato Market.

If you are a beginner, once you learn the interface you can vastly improve your learning curve. PlayMaker also has a very active community, where you can find questions and answers from users.
 2018-05-14T12:30:15.000Z 2018-05-14T12:30:15.000Z Sandy Gerber tag:gamedevelopment.tutsplus.com,2005:PostPresenter/cms-30906 Create 2D Tree Shapes With Code

What You'll Be Creating

Creating organic shapes like trees can be an interesting side project for potential game developers. You can use the same logic to create levels or other complicated logic structures. In this tutorial, we will be creating 2D tree shapes in Unity using two different approaches: Fractal and L-System.

 1. Creating 2D With 3D

Although we call these 2D tree shapes, they are essentially 3D mesh objects in Unity. The game object which has the tree script will need to have these 3D mesh components attached in order to create our tree shape. Those components are the MeshRenderer and the MeshFilter, as shown below.

With these components attached, we will be creating a new mesh using the different algorithms for fractals and L-Systems.

Creating a Mesh

A 3D mesh is created using multiple vertices which combine to form faces. To make a single face, we will need a minimum of three vertices. When we connect three vertices in a clockwise sequence, we will get a face which has a normal pointing outwards. The visibility of a face is dependent on the direction of its normal, and hence the sequence in which the vertices are passed in to create a face matters. Please read the official Unity documentation for further details regarding the creation of a mesh.

With the power of mesh creation under our belt, let's proceed to our first method for creating a 2D tree: fractal.

 2. Creating a Fractal Tree

A fractal is a shape created by repeating a pattern with varying scales. Theoretically a fractal can be an unending pattern, where the base pattern gets repeated indefinitely while its size gets reduced progressively. When it comes to a tree, the base fractal pattern can be a branch splitting into two branches. This base pattern can be repeated to create the symmetrical tree shape shown below.

We will need to stop the repetition after a certain number of iterations, and the result is obviously not a very realistic tree shape. Yet the beauty of this approach—and fractals in general—is that they can be easily created using simple recursive functions. The base pattern drawing method can recursively call itself while reducing the scale until a certain number of iterations are complete.

The Branch

The primary component in a tree shape is a branch. In our approach, we have a Branch class, which has a CreateBranch method as shown below.

private void CreateBranch(Vector3 origin, float branchLength,float branchWidth, float branchAngle, Vector3 offset, float widthDecreaseFactor) { Vector3 bottomLeft=new Vector3(origin.x,origin.y,origin.z),bottomRight=new Vector3(origin.x,origin.y,origin.z),topLeft=new Vector3(origin.x,origin.y,origin.z),topRight=new Vector3(origin.x,origin.y,origin.z); bottomLeft.x-=branchWidth*0.5f; bottomRight.x+=branchWidth*0.5f; topLeft.y=topRight.y=origin.y+branchLength; float newWidth=branchWidth*widthDecreaseFactor; topLeft.x-=newWidth*0.5f; topRight.x+=newWidth*0.5f; Vector3 axis=Vector3.back; Quaternion rotationValue = Quaternion.AngleAxis(branchAngle, axis); vertices.Add((rotationValue*(bottomLeft))+offset); vertices.Add((rotationValue*(topLeft))+offset); vertices.Add((rotationValue*(topRight))+offset); vertices.Add((rotationValue*(bottomRight))+offset); }

A branch essentially is a shape (or a Quad) with four corner vertices: bottomLeft, topLeft, topRight, and bottomRight. The CreateBranch method does the proper positioning of the branch by translating, rotating, and scaling these four vertices based on the shape, position, and rotation of the branch. The tip of the branch is tapered using the widthDecreaseFactor value. The main tree method can call this method while passing in the position and rotation values for that branch.

Fractal Tree

The FractalTreeProper class has a recursive CreateBranch method, which in turn will create the Branch class's CreateBranch constructor method.

private void CreateBranch(int currentLayer,Vector3 branchOffset, float angle, int baseVertexPointer) { if(currentLayer>=numLayers)return; float length=trunkLength; float width=trunkBaseWidth; for(int i=0;i<currentLayer;i++){ length*=lengthDecreaseFactor; width*=widthDecreaseFactor; } Branch branch=new Branch(Vector3.zero,length,width,angle, branchOffset,widthDecreaseFactor); branches.Add(branch); Vector3 tipMidPoint=new Vector3(); tipMidPoint.x=(branch.vertices[1].x+branch.vertices[2].x)*0.5f; tipMidPoint.y=(branch.vertices[1].y+branch.vertices[2].y)*0.5f; //... CreateBranch(currentLayer+1,tipMidPoint,angle+branchAngle,baseVertexPointer); CreateBranch(currentLayer+1,tipMidPoint,angle-branchAngle,baseVertexPointer); }

Each call to CreateBranch initiates two new calls to itself for its two child branches. For our example, we are using a branching angle of 30 degrees and a value of 8 as the number of branching iterations.

We use the points from these branches to create the necessary vertices, which are then used to create faces for our tree mesh.

faces=new List<int>(); vertices=new List<Vector3>(); fTree=GetComponent<MeshFilter>().mesh; fTree.name="fractal tree"; //...(in CreateBranch) if(currentLayer==0){ vertices.AddRange(branch.vertices); faces.Add(baseVertexPointer); faces.Add(baseVertexPointer+1); faces.Add(baseVertexPointer+3); faces.Add(baseVertexPointer+3); faces.Add(baseVertexPointer+1); faces.Add(baseVertexPointer+2); }else{ int vertexPointer=vertices.Count; vertices.Add(branch.vertices[1]); vertices.Add(branch.vertices[2]); int indexDelta=3; if(currentLayer!=1){ indexDelta=2; } faces.Add(baseVertexPointer-indexDelta); faces.Add(vertexPointer); faces.Add(baseVertexPointer-(indexDelta-1)); faces.Add(baseVertexPointer-(indexDelta-1)); faces.Add(vertexPointer); faces.Add(vertexPointer+1); } baseVertexPointer=vertices.Count; //... fTree.vertices=vertices.ToArray(); fTree.triangles = faces.ToArray(); fTree.RecalculateNormals();

The baseVertexPointer value is used to reuse existing vertices so that we avoid creating duplicate vertices, as each branch can have four vertices but only two of those are new ones.

By adding some randomness to the branching angle, we can create asymmetrical variants of our fractal tree as well, which can look more realistic.

 3. Creating an L-System Tree

The second method, the L-system, is an entirely different beast. It is a very complicated system which can be used to create intricately complex organic shapes or to create complex rule sets or string sequences. It stands for Lindenmayer System, the details of which can be found on Wikipedia.

The applications of L-systems include robotics and AI, and we will only be touching the tip of the iceberg while using it for our purposes. With an L-system, it is possible to create very realistic looking tree or shrub shapes manually with precise control or using automation.

The Branch component remains the same as in the fractal example, but the way in which we create branches will change.

Dissecting the L-System

L-systems are used to create complicated fractals where the patterns are not easily evident. It becomes humanly impossible to find these repeating patterns visually, but L-systems make it easier to create them programmatically. L-systems consist of a set of alphabets which combine to form a string, along with a set of rules that mutate these strings in a single iteration. Applying these rules over multiple iterations creates a long, complicated string which can act as the basis for creating our tree.

The Alphabets

For our example, we will use this alphabet to create our tree string: F, +, -, [, and ].

The Rules

For our example, we will only need one rule where the alphabet F changes into a sequence of alphabets, say F+[+FF-F-FF]-[-FF+F+F]. On every iteration, we will make this swap while keeping all the other alphabets unchanged.

The Axiom

The axiom, or the starting string, will be F. This essentially means that after the first iteration, the string will become F+[+FF-F-FF]-[-FF+F+F].

We will iterate three times to create a usable tree string as shown below.

lString="F"; rules=new Dictionary<string, string>(); rules["F"]="F+[+FF-F-FF]-[-FF+F+F]"; for(int i=0;i<iterations;i++){ lString=IterateLString(lString); } //.. string IterateLString(string currentLString){ string newLString=""; char[] chars=currentLString.ToCharArray(); for(int i=0;i<chars.Length;i++){ if(rules.ContainsKey(chars[i].ToString())){ newLString+=rules[chars[i].ToString()]; }else{ newLString+=chars[i].ToString(); } } return newLString; }

Parsing the Tree String

Now that we have the tree string using the L-system, we need to parse it to create our tree. We will look at each character in the tree string and do specific actions based on them as listed below.

On finding F, we will create a branch with current parameters of length and rotation.

On finding +, we will add to the current rotation value.

On finding -, we will subtract from the current rotation value.

On finding [, we will store the current position, length, and rotation value.

On finding ], we will restore the above values from the stored state.

We use an angle value of 25 degrees for branch rotation for our example. The CreateTree method in the LSystemTree class does the parsing. For storing and restoring states, we will be using a LevelState class which stores the necessary values along with a BranchState struct.

levelStates=new List<LevelState>(); char[] chars=lString.ToCharArray(); float currentRotation=0; float currentLength=startLength; float currentWidth=startWidth; Vector3 currentPosition=treeOrigin; int levelIndex=0; LevelState levelState=new LevelState(); levelState.position=currentPosition; levelState.levelIndex=levelIndex; levelState.width=currentWidth; levelState.length=currentLength; levelState.rotation=currentRotation; levelState.logicBranches=new List<LevelState.BranchState>(); levelStates.Add(levelState); Vector3 tipPosition=new Vector3(); Queue<LevelState> savedStates=new Queue<LevelState>(); for(int i=0;i<chars.Length;i++){ switch(chars[i]){ case 'F': if(levelState.levelIndex!=levelIndex){ foreach(LevelState ls in levelStates){ if(ls.levelIndex==levelIndex){ levelState=ls; break; } } } tipPosition.x=levelState.position.x+(currentLength*Mathf.Sin(Mathf.Deg2Rad*currentRotation)); tipPosition.y=levelState.position.y+(currentLength*Mathf.Cos(Mathf.Deg2Rad*currentRotation)); levelIndex++; LevelState.BranchState branchState=new LevelState.BranchState(); branchState.rotation=currentRotation; branchState.length=currentLength; levelState.logicBranches.Add(branchState); currentWidth*=widthDecreaseFactor; currentPosition=tipPosition; levelState=new LevelState(); levelState.position=currentPosition; levelState.levelIndex=levelIndex; levelState.width=currentWidth; levelState.length=currentLength; levelState.rotation=currentRotation; levelState.logicBranches=new List<LevelState.BranchState>(); levelStates.Add(levelState); currentLength*=lengthDecreaseFactor; break; case '+': currentRotation+=angle; break; case '-': currentRotation-=angle; break; case '[': savedStates.Enqueue(levelState); break; case ']': levelState=savedStates.Dequeue(); currentPosition=levelState.position; currentRotation=levelState.rotation; currentLength=levelState.length; currentWidth=levelState.width; levelIndex=levelState.levelIndex; break; } }

The variable levelStates stores a list of LevelState instances, where a level can be considered as a branching point. As each such branching point can have multiple branches or just one branch, we store those branches in a list logicBranches holding multiple BranchState instances. The savedStates Queue tracks the storing and restoring of different LevelStates. Once we have the logical structure for our tree in place, we can use the levelStates list to create visual branches and create the tree mesh.

for(int i=0;i<levelStates.Count;i++){ levelState=levelStates[i]; int baseVertexPointer=vertices.Count; for(int j=0;j<levelState.logicBranches.Count;j++){ LevelState.BranchState bs=levelState.logicBranches[j]; Branch branch=new Branch(Vector3.zero,bs.length,levelState.width,bs.rotation, levelState.position,widthDecreaseFactor); branches.Add(branch); if(i==0&&j==0){ vertices.AddRange(branch.vertices); faces.Add(baseVertexPointer); faces.Add(baseVertexPointer+1); faces.Add(baseVertexPointer+3); faces.Add(baseVertexPointer+3); faces.Add(baseVertexPointer+1); faces.Add(baseVertexPointer+2); baseVertexPointer=vertices.Count; }else{ int vertexPointer=vertices.Count; vertices.Add(branch.vertices[1]); vertices.Add(branch.vertices[2]); Vector2Int vertexPointerXX=GetClosestVextexIndices(branch.vertices[0],branch.vertices[3],vertices,i); faces.Add(vertexPointerXX.x); faces.Add(vertexPointer); faces.Add(vertexPointerXX.y); faces.Add(vertexPointerXX.y); faces.Add(vertexPointer); faces.Add(vertexPointer+1); } } } lTree.vertices=vertices.ToArray(); lTree.triangles = faces.ToArray(); lTree.RecalculateNormals();

The GetClosestVextexIndices method is used to find common vertices to avoid duplicates while creating the mesh.

By varying the rules slightly, we can get drastically different tree structures, as shown in the image below.

It is possible to manually create the tree string for designing a specific kind of tree, although this can be a very tedious task.

Conclusion

Playing with L-systems can be fun, and it could result in very unpredictable results as well. Try changing the rules or adding more rules to create other complicated shapes. The next logical thing to do would be to try and extend this to 3D space by replacing these 2D Quads with 3D cylinders for branches and adding the Z dimension for branching.

If you are serious about creating 2D trees, I would suggest that you look into space colonization algorithms as the next step.
 2018-04-26T09:00:00.000Z 2018-04-26T09:00:00.000Z Juwal Bose tag:gamedevelopment.tutsplus.com,2005:PostPresenter/cms-29936 Creating a VR Game in Unity

What You'll Be Creating

In this tutorial, I will show you how to create a virtual reality game using Unity 3D. Virtual reality games are popular, fun, and can take your game development skills to another level, so let's dive in!

Download Unity

If you haven't already, let's download the latest version of Unity. It is free for personal and hobby use. Unity allows you to create upload your game to many different platforms, including iOS, Android, Xbox, and Linux.

Adding the VR plugins

In order to create a VR game for your chosen platform, we will need to download a couple of plugins. For the purpose of this tutorial, I will show you how to upload to the Android platform. To upload to iOS, you will need to download Xcode.

Now let's download the Google VR SDK plugin for Unity. As of this tutorial, it is on version 1.110. You can find it on GitHub. Unzip and extract all the files into a new folder. This will help you keep your files organized.

In addition, if you don't already have it, you may need the Java SE Development Kit. Follow the instructions on the Oracle website.

Note: You may also need to download the Android SDK.

Let's Create a Project

Open up Unity to create a new project. It will ask if you would like to download an asset. Let's download the Environment Package.

Once your project is open, go to Assets > Import Package > Custom Package > Import Google VR SDK for Unity > Import.

We need to prepare our project for the VR platform. We will need to tell Unity we are building for Android and make the scene VR enabled. First, go to File > Build and choose Android. It would also be a good time to choose Landscape Left. Then click Switch Platform at the bottom and close the window.

Time to enable the VR settings. If you try to play the game before doing the above, you will receive errors. Go to Edit > Project Settings > Player, and then on the right-hand side under XR Settings, click Virtual Reality Supported.

Don't forget to choose an SDK. For this tutorial, choose Cardboard (as seen above).

Our Environment

Initially, we will be using the GVR Demo scene (shown above). Open up your assets in the Project tab and go to Scenes > GVRDemo. Once the file opens, we will be changing the environment. We will delete the following objects in the Hierarchy:

DemoSceneManager

DemoInputManager

CubeRoom

Cube

Floor Canvas

For now, we will keep everything else intact. Let's briefly discuss why, as explained by the developers at GoogleSDK.

 GvrControllerVisual provides visual feedback for the daydream controller.

 GvrEditorEmulator provides mouse-controlled head tracking emulation in the Unity editor.

 GVR Controller gives the player keyboard input.

Let's start our own environment. Save your scene and go to GameObject to add a terrain. In Projects, let's choose a grass surface and drag it onto the scene. To add some substance, let's add some hills. In the Hierarchy under Terrain, let's choose the button with the hill and the arrow pointing upwards. Now choose a brush. It's good to alternate to make your environment look real. If your hills are too pointy, use the smooth button as shown below.

Tip: Make sure your Terrain does not have Gravity chosen, or it will fly away!

The Unity asset store is a great resource for developers, and you can find it right in your project under Assets. I've downloaded two buildings. You can find them under the Free filter in the Asset Store as "Abandoned Buildings".

Tip: You can always drag an asset straight into the Hierarchy.

Let's Get Moving

Since not all VR headsets come with a controller, we will need to add an Autowalk code to have the user walk on its own. A movement will happen when you look at an object.

Once you are happy with your environment, hit Play, and you should be able to look around the world by holding the Alt button. To make our VR character move, we will need to add a script and change some settings on the Player in the Hierarchy.

First things first: choose Player in the Hierarchy. Let's Add a Component > Capsule Collider and a RigidBody. We also need to freeze the X, Y, and Z Rotation of the Rigidbody (as shown above).

Now it's time to add our script to the Player. I have attached the script to this tutorial under attached files. Save the file in your Unity folder, and then click and drag it into the Project. Now Add a Component > New Script. Type Autowalk and the script should show up. You may need to save your project and refresh the scene.

Once you add the script, it will give you an option to configure it. We will need to add a Speed of 2 and check Walk When Triggered (see below).

Test Your Game

Time to test your game on your phone. Go to File > Build Settings > Android > Build & Run. You will need to type an identifier (people usually use com.nameofyourgame). As discussed before, you will need to have the Android SDK, which is free to use.

Save your build and transfer to your phone using a USB cord. Once the game starts, you may need to hit Settings > Cardboard if it looks off.

Unity has an active economy. There are many other products that help you build out your project. The nature of the platform also makes it a great option from which you can better your skills. Whatever the case, you can see what we have available in the Envato Market.

Tip: You need USB debugging to build for Android. If you have an Android phone, navigate to Settings and then About Phone, and tap Build Number seven times. You will get a new button for developers.
 2018-01-29T12:00:13.000Z 2018-01-29T12:00:13.000Z Sandy Gerber tag:gamedevelopment.tutsplus.com,2005:PostPresenter/cms-29593 How to Create Realistic Water in Unity

What You'll Be Creating

Unity is a multi-platform game engine developed by Unity Technologies and is used to create video games and applications for several devices such as consoles, mobile devices, computers, and even websites. Unity's core advantages are its robustness, portability, and community; Unity targets several well-known APIs such as Direct3D, OpenGL, OpenGL ES, and the recent Vulkan.

Due to the aforementioned characteristics, Unity has become more and more popular among AAA software development houses and aspiring game programmers.

Unity supports several technologies and components. One of the key components is the Water system. Unity's water system allows you to add different types of water into your application or game, namely Water Basic, Water Pro, and Water4. By default, Unity includes several water prefabs (including the necessary shaders, scripts, and art assets).

This tutorial will focus on explaining how the water in Unity works, and how to use it to create vast and rich terrain environments.

Prerequisites

First, ensure you are using the latest version of Unity; otherwise, you may find small differences following the tutorial and using the physics joints.

To start this tutorial, you have two paths to choose from:

Start it right away using the available Starting Project.

Complete the previous Unity tutorial called Unity Terrain tools.

Either way, we will get you covered, but taking your time and starting in the previous one will give you more insights about Unity and its tools.

Water Basic

I'm assuming that you either started by using the current Starting Project or you have finished the previous Unity Terrain tools tutorial. If that's not the case, you can start a new project, but you must import the environmental asset package and create your own terrain. If you are using a new project, go to the main menu, Assets > Import Package and select Environment.

From now on, the tutorial is focused on the current Starting Project. By analysing the terrain, you can see that, in the center, the ground is a little bit deeper. That area was created specifically for you to create a lake. One way to do this is using the Water Basic prefab.

In the Project tab, open the Assets folder and then open Environment. Here you will find two water folders: Water and Water (Basic). Initially, you will work with Water (Basic). Open it and then open the Prefabs folder. Two prefabs are available: WaterBasicDaytime and WaterBasicNightime.

Before moving on, here's a quick explanation of prefabs. A prefab acts as a template of a game object. It allows you to create new object instances in the scene, and any edits made to a prefab asset are immediately reflected in all instances produced from it.

However, you can also override components and settings for each instance individually. This can be quite helpful if you need to have several objects of the same type in a scene or in several scenes. By using prefabs, you don't need to create every single object from scratch, and if you want to make an adjustment to it, it will automatically update all instances.

As you may have guessed by the names, you should use WaterBasicDaytime if you have a scene during the day, and you use WaterBasicNightime in nighttime scenes. Both of them work in exactly the same way, but the second one is set to be darker.

In this project you have a daytime scene, so you are going to use the WaterBasicDaytime prefab. Select the prefab with the mouse, and drag it to the scene (more or less into the hole in the ground, similar to the next figure). This will add the WaterBasicDaytime to the scene.

Next, select the water and adjust its Position and Scale.

When you have the water positioned and configured as you want, let's take a quick look at what you can do with it. If you select it and go to the Inspector tab, you will see several components: a Transform component that you have just used, a Water Basic Plane (Mesh Filter), a Mesh Renderer where the Material for the water is set, a Water Basic Script, and a Shader.

Inside the Mesh Renderer, you can change some options related to shadow generation like Cast Shadows or Receive Shadows. You can also modify several properties related to reflections. Set Cast Shadows and Receive Shadows to On. Next, for Reflection Probes, let's set it to Blend Probes And Skybox.

The WaterBasicDaytime Shader lets you set some parameters for the water, like the Wave scale and the Wave speed. You can play with those values to see some graphical changes, but for now leave the default values.

Now, in order to see the final result, place the camera in a good position. To do that, move to the Scene view and, once you have the view you want, select the Main Camera game object. Now go to the menu GameObject, and select Align With View. This will place the camera in the position you want. Press play.

From here, you can go back and change the prefab properties to see the differences between properties. Play with Cast Shadows, Wave scale, and Wave speed to sense the modifications.

Water Pro

The next step is to learn how to create and configure a lake using Water Pro. Before moving on, delete the WaterBasicDaytime game object from your scene.

Next, in your Project tab, open the Standard Assets folder and open Environment again. This time, open the Water folder. Inside you have two folders: Water and Water4. In order to use Water Pro, you must open the Water folder. Next, open the Prefabs folder.

Just like with Water Basic, you have two prefabs in the folder: WaterProDaytime and WaterProNightime. Both of them work in exactly the same way, and as aforementioned WaterProDaytime is set for daytime scenes, while WaterProNightime is set for darker environments.

Since you have a daytime scene, you should choose WaterProDaytime. Select the prefab and drag it into the scene. Again, select the WaterProDaytime game object and adjust its Position and Scale.

As soon as the lake gets a good size, you will instantly see differences in the graphical quality of the water compared to Water Basic.

When you have the water in place, please take a quick look at what you can do with it. If you select it and then look at the Inspector tab, you will see several components: a Transform component, a Water Plane Mesh, a Mesh Renderer, a Water (Script), and a Shader.

The Mesh Renderer properties are similar to the previous one. Set both Cast Shadows and Receive Shadows to On. Next, change Reflection Probes to Blend Probes And Skybox.

The water Script presents further properties that can be modified. These properties are not available for the previous water type.

You can set the Water Mode to Simple, which will make the water work like the basic water, to Reflective, which will make the water have reflection but no refraction, or Refractive, which allows both reflection and refraction. You can Disable Pixel Lights, which will reduce the quality of lighting in the reflection/refraction in order to gain an increase in performance.

You can set the Texture Size, which refers to the resolution of the generated water texture. The Clip Plane Offset value is the distance below the water that the reflected or refracted image appears. You can set the Reflect Layers affected as well as the Refract Layers. These are layer masks that control which scene objects are visible in the water. By default, all layers are selected.

In the Shader component, you can change the Wave Scale, and change the values of Reflection and Refraction Distort. These will determine the apparent height of the ripples in terms of their effect on reflected or refracted objects.

You can also set the Reflective color of the water to control the tint that will be applied to objects underwater.

If you press play, you can see your Water Pro in action. This is a way more realistic water than the Water Basic; however, in terms of computational power required, it is also more intensive.

Water4

To test Water4, you need to delete the lake you have just created.

In your Project tab, open the Standard Assets > Environment. Open the Water folder and then the Water4 folder. Next, open the Prefabs folder. Here you find two prefabs: Water4Simple and Water4Advanced.

If you select the two prefabs and compare them, you will notice that they have the same components and work in exactly the same way. Then what's the difference between the two?

Well, you can see that by selecting the water material they use. The advanced version includes additional Shore and Foam textures. These textures are applied on the crests of waves and also where terrains and other objects interrupt the wave mesh, like the shore.

Select the Water4Advanced prefab and drag it into the scene. The next thing to do is to adjust the Position and Scale of the water plane.

Note that when you add the prefab, Unity will automatically create a reflection scene game object. This game object allows you to change the water reflection in your scene. The camera component on reflection game object allows the Water4 to reflect your scene.

Now, if you select the Water4Advanced game object, you will see that you have several properties that you can change.

The first field in the Water Base (Script) component allows you to define a material for your water. You can also define the Water Quality as Low, Medium, or High. If the Edge Blend option is enabled, Water4 will blend the edges of the water mesh.

The next component is Specular Lighting. This script adjusts the specular quality of the water. As you can see, it has a reference to specular game object transform. You can use a reference to indicate any transform of a specular light source. This can be, for example, your directional light transform.

Next you have the Planar Reflection component. This one is used for real-time planar reflections. The reflections are calculated in relation to the height of the parent mesh that has this script attached. You can set several parameters as the reflection masks, turn reflect skybox on or off, or define a clear color. Let's just leave these with the default values.

Finally, you have the Gerstner Displace component, which allows you to control wave generation.

If you press the play button, you can now see the Water4 in action, creating a lake in the center of the terrain.

Conclusions

This concludes the tutorial about Unity Water. You learned about the three main types of water: Water Basic, Pro, and Water4. With this knowledge, you can now create new rich environments, or modify and improve current ones, for your next cutting-edge game or application.

Unity has an active economy. There are many other products that help you build out your project. The nature of the platform also makes it a great option from which you can improve your skills. Whatever the case, you can see everything we have available in the Envato Marketplace.

If you have further questions or comments, as always, feel free to drop a line in the comments section.
 2017-10-18T12:00:23.000Z 2017-10-18T12:00:23.000Z Orlando Pereira tag:gamedevelopment.tutsplus.com,2005:PostPresenter/cms-27588 Importing an Animated Character Into Unity 3D

What You'll Be Creating

Unity 3D is one of the most popular open-source game engines available today. Along with an easy-to-use interface, it allows you to import files from most major designing programs, such as Maya (.mb or .ma), Cinema 3D (.c4d, .c3d), Studio Max (.max), and Blender (fbx.).

At first, importing a character into Unity can seem intimidating. In this tutorial, I hope to make it simple, so that you may bring your carefully sculpted character to life!

Finding Free Animations

If you have created your own animations, that's awesome—we will discuss importing them into Unity shortly. If you've created your character or would like to purchase a stock character, let's talk about where we can find some.

Mixamo is a great option (recently purchased by Adobe). They provide basic free animations and custom bone rigging that can animate your character in minutes. Once you sign up, you can choose different characters and animation kits. Separately, you can use the free preset animations from Unity or purchase animation packages from the Unity Asset Store.

Open Unity

Since this tutorial is about importing an animated character, we won't get into the specifics about Unity. Let's open Unity by starting a new project.

Tip: Unity understands the T-Pose, so before importing your character, aim to save him in a default T-pose.

Preparing Your World

Your character may have many different components, and that's why it's important to create a new folder. Right click on the Project Window > Create > New Folder. For the purpose of this tutorial, let's name it character.

Now let's add a plane for our character to stand on. Go to GameObject >3D Object > Plane. We will also need to adjust the camera by moving the arrow for a better view.

Importing Your Character

Time to import your character. Click and drag your character's file (fbx, cd3, etc.) into the folder you created in Unity. All of your character's elements, including materials, will be imported into the same file.

Setting Up Your Rig

To set up the rig, right click your character and choose humanoid. A new window will open with your character, and this is where Unity attempts to match your character's rig (muscles and bones).

A good rig match will show in green. See the example below.

After your character is configured, click Done and Configure. Save your scene. We can now drag your character into the game world.

Animator Controller Basics

Time to add his animation. Go to Create > Animator Controller, and name it MyController.

After you add the animator controller, you will see a new tab. This is where we will add our character's animation. You may have multiple animations, but for the purpose of this tutorial we will talk about adding one. Each State (box) will represent an animation.

Click on the clock to the right of Motion. A window will open with your imported animations, so click and drag one into that box.

Tip: The default animation will be in orange.

To edit your animation settings, double click on the State. A box will open under the Inspector Window. Here you can edit the speed and loop time if you wish your animation to loop.

When you right click on a state, you can create transitions. This is used for multiple animations—for example, walk to run. Let's right click and create a New State, and then add a transition from Entry to New State. See the example above.

Tip: You can use your middle mouse button to zoom in and out.

Go to the Scene tab and click on your character. You can now drag your animator controller into the controller box in the Inspector Window. See the example above.

Let's Play

In conclusion, you should now have an understanding of how to import and add an animation to the animator controller.

Time to see our character in action. Click the Play button on top of the Scene Window. Congratulations! You have just imported your animated character into Unity!
 2017-09-20T13:00:44.000Z 2017-09-20T13:00:44.000Z Sandy Gerber tag:gamedevelopment.tutsplus.com,2005:PostPresenter/cms-27693 Introduction to Vuforia on Unity for Creating Augmented Reality Applications

What You'll Be Creating

This tutorial is going to cover how to implement a basic augmented reality application with Vuforia SDK on Unity. Throughout the tutorial, you are going to learn how to generate a scene compatible with Vuforia and how to implement various scripts, including ray-tracing, in order to be able to interact with the object within the scene.

Creating a Developer Account

Before starting off, you need to register for a Vuforia developer account. Go to the Vuforia Developer Portal to create an account.

Once you create your account, it is time to download the Unity package of Vuforia. Go to the download page and download the specific package for Unity.

Creating an Image Target

An image target is required in order for a device's camera to recognize a reference and track it. The orientation and actual size of the target image directly affect the same attributes of the superimposed images.

Any image can be assigned as a target. However, the features of the target image effectively determine how well the target is tracked. In this tutorial, we are going to use an online tool to generate feature-rich target images. Generate an image target by using the Augmented Reality Marker Generator online tool, and save the image on your computer.

Preparing the Unity Scene

Vuforia Package

Create a new 3D unity project and then double-click the Unity package you downloaded for Vuforia. This will prompt the following window. Click All to select all the content of the package, and then hit Import. This is going to import all the necessary tools for the AR application.

Image Target

The next step is to import the image target files. In order to obtain the image target files, we need to use the Vuforia developer page.

Go to the Vuforia Developer Portal and then log in to your account. Under the Develop tab, you will see the Target Manager. First you need to add a database. Use the designated button and add a database.

Name your database as you wish, and select Device as the type.

Now we are ready to add a target in this database. Click on the Add Target button, and the following window will appear. The type should be selected as Single Image in our case. Select the image target that we generated by using the online tool. If you have any trouble uploading the file, try converting it to .jpg file format and uploading again.

Width is a crucial parameter. This should match the real size of the target image that you will be eventually printing on paper. I set the width to 40. There is no unit since it matches the unit of your scene.

Once you add the target into your database, Vuforia rates your target. With the target image generator we used, features are high and therefore it gets 5 stars, which means it's easy for Vuforia to recognize and track this target.

Now you need to download this database. To do so, hit the Download Database button and select Unity Editor as the development platform.

Once you've downloaded the database, double click on it and import all the content to the Unity scene we are working on.

ARCamera Object

We start by adding the ARCamera object of Vuforia to our scene. To do so, simply follow the Assets > Vuforia > Prefabs directory and add the ARCamera object by dragging and dropping to the scene.

Select the ARCamera object and under the Inspector tab, you will see the App License Key section. This license key will be obtained from the Vuforia developer portal.

Log in to your Vuforia account on the Developer Portal and under the Develop tab, you will find the License Manager section. Click the Add License Key button. On the following page, select Development as the project type and define an application name for your project. This name is not crucial, and you can alter it later on if you wish.

Hit Next, and then confirm your license key on the next page.

Select the license you've just created. It will reveal the license key that we need to copy and paste to the ARCamera object. Copy this license and then paste it into the App License Key section under the ARCamera settings.

Under Database Load Behaviour, check the Load ARdemo Database option. Once you check it, another option called Activate will appear right under it. Check this option as well.

The ARdemo part of the Load ARdemo Database option depends on how you named your database.

Image Target Object

The second object we need in our scene is the Image Target object.

Under the Assets > Vuforia > Prefabs directory, you will also find the "ImageTarget" object. Add this object to your scene and select it to reveal the options.

Under the Image Target Behaviour section, you will see the Database option. Select your database from the dropdown menu and select the specific image target you want to assign to the image target object from the "Image Target" option's dropdown menu. If you have multiple image targets for one database, they will all be listed here.

The width and height parameters will be automatically set depending on the value you assigned when creating the image targets in Vuforia's developer portal.

Augmenting Graphics

The next step is to create the graphics and tie them to the image target. You can either create a GameObject or you can import your own 3D model into Unity and use it. In this tutorial we are going to use a simple 3D cube object for the sake of simplicity.

Add a cube object to the scene as shown in the following figure.

Set its x, y and z parameters for the Scale option under Transform to 40, so that it matches the size of the image target we generated.

If you set another width value for your image target when generating it in the developer portal, use the value you selected in order to match the full size of the image target.

The last step to get our AR app working is to set the cube object as the child of the image target. To do so, simply drag the cube object and drop it on the imageTarget object under the hierarchy menu.

The final state of the scene should be as follows:

Now hit the Play button to run your application. It will use your webcam. Either get the target image printed or open it from your phone so that Vuforia can detect it through your webcam. I did the latter and opened the target image from my phone.

Here is the actual screenshot of the view of the webcam. You can see that the cube object covers the whole target image, since we matched the scaling factor values both for the 3D object and the target image.

Interaction Scripts

So far, we've developed a basic AR application that recognizes and tracks our target image and displays the designated 3D graphics. However, for a complete AR application, we also need to be able to interact with the objects, augmenting the reality.

For this purpose, we need to be able to detect where we clicked—or touched, in the case of a mobile device. We'll do this by implementing a ray-tracer.

First, create a folder named "scripts" under Assets to keep everything organized. We are going to store our script files in this folder. Then create a C# Script file in this folder. Name it "rayTracer". Naming is important due to the fact that the following code should match this specific file name. If you prefer to use a different name for your script file, you should also change the provided code accordingly.

Ray-Tracer Script

Copy and paste the following code into the C# Script file you have just created and named "rayTracer".

using UnityEngine; using System.Collections; using System.Collections.Generic; public class rayTracer : MonoBehaviour { private List<GameObject> touchList = new List<GameObject>(); private GameObject[] touchPrev; private RaycastHit hit; void Update () { #if UNITY_EDITOR if (Input.GetMouseButton(0) || Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0)) { touchPrev = new GameObject[touchList.Count]; touchList.CopyTo (touchPrev); touchList.Clear (); Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); //Debug.DrawRay(ray.origin, ray.direction*10000, Color.green, 10, false); if (Physics.Raycast (ray, out hit)) { GameObject recipient = hit.transform.gameObject; touchList.Add (recipient); if (Input.GetMouseButtonDown(0)) { recipient.SendMessage ("touchBegan", hit.point, SendMessageOptions.DontRequireReceiver); } if (Input.GetMouseButtonUp(0)) { recipient.SendMessage ("touchEnded", hit.point, SendMessageOptions.DontRequireReceiver); } if (Input.GetMouseButton(0)) { recipient.SendMessage ("touchStay", hit.point, SendMessageOptions.DontRequireReceiver); } } foreach (GameObject g in touchPrev) { if(!touchList.Contains(g)){ g.SendMessage ("touchExit", hit.point, SendMessageOptions.DontRequireReceiver); } } } #endif if (Input.touchCount > 0) { touchPrev = new GameObject[touchList.Count]; touchList.CopyTo (touchPrev); touchList.Clear (); foreach (Touch touch in Input.touches) { Ray ray = Camera.main.ScreenPointToRay (touch.position); if (Physics.Raycast (ray, out hit)) { GameObject recipient = hit.transform.gameObject; touchList.Add (recipient); if (touch.phase == TouchPhase.Began) { recipient.SendMessage ("touchBegan", hit.point, SendMessageOptions.DontRequireReceiver); } if (touch.phase == TouchPhase.Ended) { recipient.SendMessage ("touchEnded", hit.point, SendMessageOptions.DontRequireReceiver); } if (touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved) { recipient.SendMessage ("touchStay", hit.point, SendMessageOptions.DontRequireReceiver); } if (touch.phase == TouchPhase.Canceled) { recipient.SendMessage ("touchExit", hit.point, SendMessageOptions.DontRequireReceiver); } } } foreach (GameObject g in touchPrev) { if(!touchList.Contains(g)){ g.SendMessage ("touchExit", hit.point, SendMessageOptions.DontRequireReceiver); } } } } }

This script detects both mouse clicks if you are working on the Unity editor and touch inputs if you have deployed your application on a mobile device with a touch screen.

Once you've created your rayTracer script, you need to activate it by assigning it to one of the objects in the scene. I selected the ARCamera object and added the rayTracer scripts as a component by using the Add Component button under the Inspector tab.

Object Material

Now we are going to assign a material to our Cube object and change the color of the material upon interaction with the cube.

Under Assets, create a material and name it as you wish.

Now assign this material by dragging and dropping over the cube object.

Interaction Script

Create a new C# Script under the scripts folder and name it "interaction".

Copy the following C# code into your "interaction" script file and then add this script file to the cube object as a component, just as we did with the "rayTracer" script file. However, this time it should be a component of the cube object—this is important in order to be able to only interact with the cube object.

using UnityEngine; using System.Collections; public class interaction : MonoBehaviour { public static Color defaultColor; public static Color selectedColor; public static Material mat; void Start(){ mat = GetComponent<Renderer> ().material; mat.SetFloat("_Mode", 2); mat.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); mat.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); mat.SetInt("_ZWrite", 0); mat.DisableKeyword("_ALPHATEST_ON"); mat.EnableKeyword("_ALPHABLEND_ON"); mat.DisableKeyword("_ALPHAPREMULTIPLY_ON"); mat.renderQueue = 3000; defaultColor = new Color32 (255, 255, 255, 255); selectedColor = new Color32 (255, 0, 0, 255); mat.color = defaultColor; } void touchBegan(){ mat.color = selectedColor; } void touchEnded(){ mat.color = defaultColor; } void touchStay(){ mat.color = selectedColor; } void touchExit(){ mat.color = defaultColor; } }

In this "interaction" script, we are referring to the material of the cube object as "mat".

We created two different material objects named defaultColor and selectedColor. defaultColor is selected to be white, as the RGBA parameters indicate, which are (255, 255, 255, 255).

We initialize the cube object's material color as defaultColor by the following line:

mat.color = defaultColor;

We have four different functions for four different states:

 touchBegan() is called at the instant you touched on the object.

 touchEnded() is called when you release your finger.

 touchStay() is called right after you touched on the object—this function follows touchBegan(). So, if you assign different colors to your material in these functions, you are unlikely to see the color assigned in the touchStay() function, since it is the very first instant the touch is recognized.

 touchExit() is called when you drag your finger out of the cube object's surface, instead of releasing your finger, which calls the touchEnded() function as explained above.

In our code, when we touch on the cube object, we assign the selectedColor object to mat.color, which is the color of our cube object's material.

By assigning the selectedColor within the touchStay() function, we make sure that the color of the cube object will be equal to selectedColor as long as we keep our finger on the cube object. If we release our finger or drag it out of the cube object, we assign defaultColor to the material's color parameter by calling the touchEnded() or touchExit() functions in accordance with the action we took.

Now run the project and click on the cube object once the target image is recognized and the cube object has appeared. It should turn red and white again when you release your click or move it out of the cube object's surface.

You can experiment with different colors for the four different actions to comprehend them thoroughly.

Conclusion

In this tutorial, we've gone through an introduction to the Vuforia SDK for Unity along with its developer portal, and we've seen how to generate a target image and an appropriate license key.

On top of that, we generated custom script files in order to be able to interact with the augmented graphics. This tutorial is just an introduction to enable you to start using Vuforia with Unity and creating your own AR applications.
 2017-07-13T12:00:15.000Z 2017-07-13T12:00:15.000Z Dogacan Bilgili tag:gamedevelopment.tutsplus.com,2005:PostPresenter/cms-28623 Unity Terrain Engine Tools

What You'll Be Creating

Unity is a multi-platform game engine developed by Unity Technologies and is used to create video games and applications for a multitude of devices (PC, consoles, mobile devices, and even websites). Unity's core advantages are its robustness and portability; Unity targets several known APIs such as Direct3D, OpenGL, OpenGL ES, and the recent Vulkan.

Due to the aforementioned characteristics, Unity has become more and more popular among AAA software development houses and aspiring game programmers.

Unity supports several technologies and components. One of the key components is the terrain engine system. Unity's terrain system allows you to create vast landscapes for your games or applications. You can use a selection of tools available to create terrains easily and quickly.

This tutorial will focus on explaining how terrain engine tools work, and how to use them to create vast and rich terrain environments.

Prerequisites

First, ensure you have the latest version of Unity. In this tutorial we're using version 5.6. Make sure that you are using the latest Unity version; otherwise you may find small differences following the tutorial and using the physics joints.

For this tutorial, you will not use any starter file. The goal is to create a new project and perform the tutorial from there.

The Terrain Tools

The first step is to create a new Unity project. Now add a new scene (File > New Scene). The new scene has been created with two game objects, the Main Camera and a Directional Light (Unity 5 will automatically add a skybox into the scene).

Now, in order to add a terrain game object, go to the GameObject menu, and select 3D Object > Terrain. This will add a flat plane (called Terrain) into your scene. This plane is the mesh that we are going to sculpt in order to create your level terrain.

If you check your Assets directory (bottom part of Unity), you will see that a New Terrain file was created.

Select the Terrain and look at the Inspector tab. You will see that the terrain has three components: Transform, the Terrain script, and the Terrain Collider component.

The terrain component provides you the tools you need to edit your terrain. All the tools on the toolbar, with the exception of the tree placement tool and the settings panel, provide a set of "brushes" and settings for brush size and opacity, just like painting tools from a normal image editor. This allows you to sculpt your terrain similarly to a painting tool.

If you select any brush under the Terrain component and mouse over the terrain, you will see a blue area projected on the terrain. This lets you know the area of the terrain that your brush will affect.

As you may have already realised, the Terrain is quite big. To navigate through the Scene, you can use the mouse and keyboard. Inside the Scene tab, press and hold your Right mouse button (the cursor should change to an eye).

While holding the mouse button:

You can change the angle of your view by moving the mouse.

Use the W, S, A, D keys to move around the 3D scene.

Before you start exploring the terrain tools, let's take a look at the Terrain properties. The last button on the Terrain component (inside the Inspector) will show you the base parameters of the terrain.

The properties are divided into sections:

Base Terrain

Tree & Detail Objects

Wind Settings for Grass

Resolution

Heightmap

Inside the first section Base Terrain, you will find several properties and parameters.

The Draw option toggles the rendering of the terrain on or off. The Pixel Error represents the accuracy value of the mapping between the terrain maps (for example textures, heightmaps, and generated terrain). Higher values represent lower accuracy, and lower values will result in rendering overhead. It is your responsibility to balance this value in order to create a nice, rich environment.

The Base Map dist. is the maximum distance at which terrain textures will be displayed at full resolution. You can set shadows on or off by selecting Cast Shadows.

Next, we have Material. Here you set the material that is going to be used to render the terrain. This will affect how the color channels of a terrain texture are interpreted. You can select:

 Built In Standard represents the Physically-Based Rendering material that was introduced in Unity 5. If you select this option, for each splat layer, you can use one texture for albedo and smoothness, one texture for normal, and one scalar value to tweak the metalness. Keep in mind that if "Overwrite Smoothness" is checked, instead of reading from texture maps, the smoothness of the entire terrain will be controlled only by the Smoothness value.

 Built In Legacy Diffuse represents the legacy built-in terrain material from previous Unity releases (Unity 4 and backwards). It uses a Lambert lighting model and has optional normal map support.

 Built In Legacy Specular uses the Blinn-Phong lighting model (please consult this previous Unity 5 lightning tutorial), and has optional normal map support. This option also allows you to specify the overall specular color and shininess for the terrain.

 Custom option uses a custom material of your choice to render the terrain. This material should be a shader that is orientated for terrain rendering. This is an option that I only recommend to advanced users. However, if you want to give it a try, take a look at the source code of some of the built-in terrain shaders and make modifications on top of them.

You can also set Reflection Probes for some materials, but they will only be used when you're using a built-in standard material or a custom material which supports rendering with reflection. The options for reflection probes are:

 Off: Reflection probes are disabled, and only the skybox will be used for reflection.

 Blend Probes: Reflection probes are enabled. The blending occurs only between probes. Default reflection will be used if there are no reflection probes nearby, but there will be no blending between default reflection and probe.

 Blend Probes And Skybox: Reflection probes are enabled. Blending occurs between probes or probes and default reflection.

 Simple: Reflection probes are enabled, but no blending will occur between probes when there are two overlapping volumes.

Finally, the last parameter in this section is Thickness. This value specifies how much the terrain collision volume should extend along the negative Y-axis. Objects are considered colliding with the terrain from the surface to a depth equal to the thickness. This helps to prevent high-speed moving objects from penetrating into the terrain without using expensive continuous collision detection.

The next settings section is Tree & Detail Objects.

The first option is Draw. Here, you can set the draw of the details on or off. Basically, it tells the engine if you want trees and grass to be drawn or not. Next, you have Bake Light Probes for trees. If you enable this option, Unity will create light probes at the position of each tree. The probes will then be applied to the rendering of the trees. If you disable this option, trees will still be affected by light group probes. Take note that this option is only available for trees that have light probes enabled on their prefabs.

The Detail Distance is the distance from the camera beyond which details will be culled. Detail Density represents the number of detail objects in a given unit of area. Tree Distance represents the distance from the camera beyond which trees will be culled. The Billboard Start is the distance from the camera at which 3D tree objects will be replaced by billboard images. The Fade Length represents the distance over which trees will transition between 3D objects and billboards. Finally, the Max Mesh Trees is the maximum number of visible trees that will be represented as solid 3D meshes.

Moving on, you'll see the Wind Settings for Grass section.

Speed defines the speed of the wind as it blows grass. The Size represents the ripple size on grassy areas. Bending lets you define the degree to which grass objects are bent by the wind. Grass Tint lets you select the overall color tint applied to grass objects.

Inside the Resolution section you will find several resolution properties, namely the Terrain Width, Length, and Height. All three are very explicit of their meaning. The Heightmap Resolution is the pixel resolution of the terrain's height map. It should be a power of 2 plus 1, for example, 513, where 512 is a power of 2, and you add 1.

Detail Resolution lets you define the resolution of the map. Higher resolutions will give you smaller and more detailed grass patches. The Detail Resolution per Patch sets the length and width of the square of patches rendered on a single draw call. The Control Texture Resolution is the resolution of the splat map that controls the blending of the different terrain textures. Finally, the Base Texture Resolution sets the resolution of the composite texture used on the terrain when viewed from a distance superior to the base map distance.

The last section is Heightmap. Here you can import a heightmap raw file or export your current terrain into a heightmap raw file. This can be very useful if you want to use external third-party software to interact with your application or game.

Height Tools

Before you move on to the height tools, remember that you must set the resolution settings first. Otherwise, if you try to change them later, all of the sculpting of the terrain will be lost.

The first three tools on the Terrain Inspector toolbar are the height tools. These tools are used to paint height changes onto the terrain.

They provide a set of "brushes" with settings for Brush Size and Opacity; these tools are very similar to painting tools from any image editor. This allows you to paint detail in the terrain, as if you were painting an image.

If you move your cursor to the Scene tab, you will see a blue area projected on the terrain. This lets you know the area of the terrain that your brush will affect.

The first tool is Raise / Lower Height. When painting with this tool, the height of the terrain will be increased as you sweep the mouse over it. If you hold the mouse in one particular area, the height will accumulate. Such an effect can be visualized in the following image.

To lower the terrain, just hold the Shift key while painting with the tool, and this will lower the height of your terrain.

The second tool on the terrain editor is Paint Height. This tool is used to set a specific height for an area of the terrain.

It works in a similar way to the Raise/Lower tool, but it has an additional property to set the target Height. You can select the desired Height by changing the value of the Height parameter. The Flatten button next to the height property will level the whole terrain to the chosen Height.

Finally, the third tool is Smooth Height. This tool will not drastically increase or decrease the height of the terrain; instead, it will soften the landscape and reduce the appearance of abrupt changes. This tool is particularly useful when you have painted detail using one of the noisier brushes, since these brushes tend to create sharp, jagged rocks in the landscape, and you can use this tool to soften them.

It is now time to take some time and create your own sculpted terrain. Try to use the aforementioned three tools to create a nice mountain terrain.

Paint Texture Tool

With the terrain sculpted, is now time to texture it.

Before moving on, you need to import the environment assets that are available with Unity 5. To do that, select Assets > Import Package, and select Environment. Click Import to import all environmental assets.

Unity allows you to paint your terrains with textures. You can paint your terrain with different textures in different areas. For example, you can have a texture for rock, another for sand, and another for grass. The textures can be applied with different transparency, which means that you can have smooth transitions between two textures. In order to achieve the best results, you should paint your terrain with seamless textures.

As you may have noticed on the Inspector tab, the Paint Texture tool has several brushes, and lets you change the Brush Size, the Opacity, and the Target Strength.

The first time you use the paint Texture Tool, there won't be any textures to choose from. The first thing you need to do is to add a new texture into your pallet. To do this, click on the Edit Textures button and select Add Texture. A new window will appear.

As you can see, on this window you can Select the texture you want to use and its normal map, if you have one. Click on the square under texture and select your texture. A window will pop up to let you select the texture. Select the SandAlbedo texture and click Add.

Your terrain should now have a sand look. Note that you can always modify it on the edit texture option, or remove it.

The first texture you create should always be the base texture for the terrain. The complete list of textures used in this example are:

SandAlbedo

GrassHillAlbedo

GrassRockAlbedo

MudRockyAlbedo

CliffAlbedo

All of them are part of the environmental imported assets and can be found in the same way as the SandAbedo texture. Go ahead and import them all.

When you have all the textures imported, it is now time to texture your terrain as you want. Select a texture and paint the desired environment. An example of a textured map is the following.

When you are satisfied with the result, move on to the next section.

Paint Tree Tool

Now that you have your terrain painted, it's time to add some trees to it. Unity 3D allows you to put trees on your terrain in the same way as you painted the textures. Using billboarding settings for distant trees, Unity maintains a good rendering performance, allowing you to have dense forests with thousands of trees.

To start painting trees, select your Terrain from the Hierarchy tab, and on the Inspector tab, select the fifth button.

Similar to textures, you also need to add the trees. Click on Edit Trees > Add Tree.

Unity will ask you for the prefab of the tree you want to use. Click on the small circle, and another window will show up. This time, it will show you all the prefabs you have in your project.

Select the Broadleaf_desktop tree prefab and click Add. This will close the prefab window and add the selected tree into the project.

You can now select the palm tree to paint it onto your terrain.

Under the Settings, you will find several parameters that you can adjust while you are placing trees in your scene. Brush Size defines the area you will paint, while Tree Density defines the number of trees you will have in the painted area. High values will mean more trees. Tree Height will allow you to define how the height changes. You can set it to random and use an interval of values, or you can set a specific value. You can Lock Width to Height of the trees, in order to make them have the same aspect ratio. You can also randomize the tree rotation orientation using the Random Tree Rotation option. Also, the tree rotation can be set to random.

Inside the Lighting section you can set how the lightmaps are generated for your trees.

In order to paint the trees in the terrain, move the mouse over into your scene view. The blue area represents the brush. With a tree type selected, press the left mouse button on the terrain and start creating trees.

To erase trees from a certain area, hold Shift and use the left mouse button. This will clear all trees in the brush area. If you just want to erase a certain type of tree, hold Control instead of Shift. This will clear just the selected tree type.

You can always change or delete a type of tree by selecting it and clicking on the edit tree button. To modify a tree, click on edit, and to delete it, click on remove.

Finally, you will notice that inside the Terrain Collider component, you have a field named Enable Tree Colliders. By selection this option, you are enabling collisions between other game objects and the trees.

If you don't want to paint the trees manually, you can use the Mass Place Trees button. If you click there, a new window will pop up. Unity will then ask you for a number of trees to create. Set the Number of Trees and click on Place. Unity will then randomly place the trees in your terrain.

The next step is being creative and populating your terrain with trees. In order to create different trees, you can also add new trees like the Palm_Desktop, Broadleaf_Mobile and Conifer_Desktop. For that, use the option Edit Trees under the Trees menu (inside Inspector).

You can create something like the following image (or something completely different).

When you are ready, you can move on to the next step.

Paint Details Tool

Unity allows the terrains to have grass clumps and other small objects, such as rocks, covering its surface. The grass is rendered using 2D images, while other objects are usually standard meshes.

To add details to the terrain, select your terrain object from the hierarchy. Inside the Inspector tab, click on the sixth button, the one with the flowers.

As you can see, you now have a similar interface to the Height Tools. Here you also have a set of brushes that you can choose from in order to paint a list of details.

Since you don't have any object details selected, let's add them by clicking on Edit Details > Add Grass Texture.

This will open a window where you can set several properties for your grass. Detail Texture lets you define the texture that you will use for your grass. You can also define several properties like Max Width, Min Width, Max Height, Min Height, Noise Spread, Healthy Color, Dry Color, and Billboard. All these properties will define how your grass will look.

For this tutorial, you can leave the default options or change them at your will.

Click on the circle in front of the Detail Texture field. This will open a new window. Search for the GrassFrond01AlbedoAlpha, select it, and click Add.

Just like for the trees, you can use several brushes to paint the grass. You can set different Brush Sizes and change the brush Opacity and the Target Strength.

It is now time to be creative and paint grass onto the terrain.

If you want to add a mesh to paint detail on your terrain, for example rocks, you need the repeat the same process you did with importing the grass. However, this time, when you click on Edit Details, choose Add Detail Mesh. This will open a window where you can specify several parameters of the detail mesh, very similar to the one you used to import the grass.

Unfortunately, the environment assets do not include any rock prefab, so you will not be able to paint rocks directly. However, you can search for some rocks over at the Unity Asset Store, since it is a great place to find free assets.

Conclusion

This concludes the tutorial about Unity Terrain Tools. You learned about several terrain tools and configurations. With this knowledge, you can now create, modify and improve current or new terrains for your next cutting-edge game or application.

Unity has an active economy. There are many other products that help you build out your project. The nature of the platform also makes it a great option from which you can improve your skills. Whatever the case, you can see everything we have available in the Envato Marketplace.

If you have further questions or comments, as always, feel free to drop a line in the comments section.
 2017-05-30T12:00:01.000Z 2017-05-30T12:00:01.000Z Orlando Pereira tag:gamedevelopment.tutsplus.com,2005:PostPresenter/cms-28744 Tips and Tricks for Augmented Reality With Unity and Vuforia
Hello, Augmented Reality traveller! In this post, I'll show you some cool features of Vuforia that make it possible to create engaging AR apps. We'll take a look at Cube and Cylinder Targets, Smart Terrain, VuMarks, and more. We won't dive deep into any of those subjects, but I'll try to cover enough to get you started.

If you aren't familiar with Vuforia's main concepts, check out some of my earlier posts. They'll get you started building your first app with Vuforia, right from scratch.

Pokémon GO Style Augmented Reality With Vuforia

With the viral success of Pokemon GO, everybody's been talking about augmented reality. In this tutorial we'll look at using Vuforia for augmented reality....

 <address class="posts__post-author">Tin Megali</address> <time class="posts__post-publication-date" datetime="2016-09-12 12:01:07 UTC" title="12 Sep 2016">12 Sep 2016</time>

Mobile Development

Create a Pokémon GO Style Augmented Reality Game With Vuforia

In this tutorial we'll start to build an app with Augmented Reality using Vuforia on Unity 3D. We'll learn how to set up Vuforia and start developing an AR...

 <address class="posts__post-author">Tin Megali</address> <time class="posts__post-publication-date" datetime="2016-09-28 12:59:40 UTC" title="28 Sep 2016">28 Sep 2016</time>

Mobile Development

Create a Pokémon GO Style Augmented Reality Game With Vuforia: Part 2

With the viral success of Pokemon GO, everybody's been talking about augmented reality. In this tutorial we'll finish creating an AR game that can be easily...

 <address class="posts__post-author">Tin Megali</address> <time class="posts__post-publication-date" datetime="2016-10-05 23:47:23 UTC" title="05 Oct 2016">05 Oct 2016</time>

Mobile Development

Create a Pokémon GO Style Augmented Reality Game With Vuforia: Image Targets

In this series, we've been building an app with Augmented Reality using Vuforia on Unity 3D. Now, we'll improve our game with Vuforia's Image Target resource.

 <address class="posts__post-author">Tin Megali</address> <time class="posts__post-publication-date" datetime="2017-03-13 15:03:55 UTC" title="13 Mar 2017">13 Mar 2017</time>

Augmented Reality

 1. Setting Up Vuforia on Unity

This section is just a review for those who have used Vuforia in the past. If you're already familiar with the process of preparing a Unity project for Vuforia, feel free to skip this section.

Before using any of Vuforia's resources on Unity, you'll have to get the framework set up. First of all, you'll have to download and import the Vuforia package for Unity.

Then you'll need to create a License Key for the project in Vuforia's License Manager. Once it's created, you'll take the key and insert it on an ARCamera prefab, and that's it. Now you can start playing around with Vuforia.

I cover this process in depth with my tutorial Create a Pokémon GO Style Augmented Reality Game With Vuforia.

Create a Pokémon GO Style Augmented Reality Game With Vuforia

In this tutorial we'll start to build an app with Augmented Reality using Vuforia on Unity 3D. We'll learn how to set up Vuforia and start developing an AR...

 <address class="posts__post-author">Tin Megali</address> <time class="posts__post-publication-date" datetime="2016-09-28 12:59:40 UTC" title="28 Sep 2016">28 Sep 2016</time>

Mobile Development

 2. Designing an ImageTarget

There are multiple ways to create Augmented Reality experiences on Vuforia, and almost all of them rely on some kind of Target that must be recognized by Vuforia's algorithm to start the augmentation process. You can design a target yourself and submit it to Vuforia's Target Manager, making it recognizable by the system. However, this design must conform to some guidelines, otherwise the target won't be tracked easily, or it might not even be recognized at all.

You especially need to know how to design an ImageTarget. That's because a lot of other kinds of Vuforia targets are composed of multiple ImageTargets arranged in some specific position and order with a MultiTarget.

There are three main rules that an ImageTarget must comply with:

It must be rich in detail.

It must have a good contrast, with bright and dark regions.

No repetitive patterns can be present.

In the background, Vuforia creates an arrangement of the image using its features, and then the algorithm can find such patterns and track the targets. Roughly, a feature in an image is a sharpened angle, like a box corner or the tip of a star. The quantity of features in an image is directly connected to its 'trackability'.

However, it's important to understand that even hundreds of features in an image won't help if those features are arranged in a pattern. The ImageTargets need some grade of randomness and chaos to be properly recognized.

If you keep those rules in mind, you'll be able to create excellent ImageTargets, but if you need to know a little more, read the documentation.

 3. Using MultiTarget

Also known as Cuboid Target, the MultiTarget consists of a series of ImageTargets in a defined geometric arrangement. This arrangement allows Vuforia's algorithm to track the targets at the same time, creating a volumetric reference. MultiTarget can be very useful in marketing campaigns to promote consumer interaction with product packages and so on.

3.1 Designing a MultiTarget

Basically, a MultiTarget design must conform to the same rules as an ImageTarget, adding two other concerns: the Depth of the box and its Geometric consistency.

The box's Depth should be at least half of its width. This is only a recommendation, and it will work if it's a little smaller than that, but it's interesting to keep that in mind.

Also, Vuforia's algorithm expects consistency on all parts of the MultiTarget. That means that all of the sides of the box are expected to be in place. If this isn't possible, it would be possible to keep the removable part blank when creating the target in Target Manager. A cereal box lid, for example, could be left blank, otherwise once the lid was open it could generate inconsistencies during the augmentation.

3.2 Creating a MultiTarget

The first step is to add or select a database in Vuforia's Target Manager. Select the database and click on Add Target, selecting the Cuboid option and setting its Width, Height, Length, and Name.

After the MultiTarget has been created, select it and set its ImageTargets. As I mentioned, a MultiTarget is composed of a series of ImageTargets adjusted in a specific position. Each part of the cuboid must contain an image, and each image should comply with the cuboid's proportion, defined when the target was created.

When the Cuboid is set, you'll be ready to go. Just download the database and import it to Unity. To use it, drag a MultiTarget prefab to the stage, and select the downloaded database and Cuboid Target. To learn more about MultiTarget, take a look at the documentation.

 4. Cylinder Targets

According to the Vuforia documentation, "CylinderTargets enable you to detect and track images rolled into cylindrical and conical shapes." You can use this kind of interaction to create engagement with product packages, like soda cans or any other cylindrical product.

4.1 Designing a Cylinder Target

A CylinderTarget is also based on the ImageTarget, hence its design should conform to those rules. The top and bottom of the cylinder must be square images that will be marked by the Target Manager system. As with MultiTarget, you should consider the target's consistency, meaning that if a part of the object can be removed, it would be helpful to leave it blank on the manager.

 4.2 Creating a Cylinder Target

This kind of target is created in two steps. The first one is to Add or Select a database in Vuforia's Target Manager, add a new Target, selecting the Cylinder option, and set its Dimensions and Name.

Next, you'll need to select the CylinderTarget you created and upload images to it. You can upload one image for the side, one for the bottom, and one for the top. Just click on the desired section and upload the image.

However, the image must respect the cylinder's ratio. It's possible that your first attempt won't work. But fear not, the Vuforia system will give you the correct ratio, and you can adjust your image proportions accordingly. For example, for a cylinder with width of 1 and height of 2, the ratio is 1.571. On a target side, the image's height is equal to the width divided by the ratio. Once the ratio is correct, your upload will succeed.

Once the CylinderTarget is defined, you can use it. You'll only have to download and import the database to Unity, and then drag a Vuforia CylinderTarget prefab to your scene, and you're ready to go.

 5. Smart Terrain

The SmartTerrain is a feature exclusive to Unity that enables you to reconstruct and augment your physical environment. The feature reconstructs, recognizes, and tracks physical objects and surfaces. Those recognized objects can be used as terrain in Unity, opening up interesting possibilities for games and experiences.

The experience is started when some kind of Vuforia target is tracked. It could start when the device tracks an ImageTarget , a CylinderTarget, or any other type of target.

Once started, the system will recognize objects distributed around the target and set the game stage considering those objects tracked. The terrain is then virtually projected over the scanned objects, and the experience begins.

Smart Terrain can recognize simple objects like boxes and cylinders, as long as they conform to Vuforia standards, putting those objects directly on the game stage and using them as part of the scene.

Those kinds of objects are called Props by the SmartTerrain system, and their size can be as small as a soup can or as big as a large cereal box. Transparent objects such as glass are not supported.

SmartTerrain works in three phases:

 Staging: the user distributes the target and the props.

 Scanning: the stage and props used in the setting are captured and reconstructed by the Smart Terrain tracker.

 Tracking: the terrain is augmented in real time by the Unity scene you've developed.

The creation process of a SmartTerrain experience is straightforward, but it takes a lot of steps. Since the Vuforia team provides us with an excellent step-by-step guide to creating a Smart Terrain experience in Unity, we won't dive into the creation process here.

If you want to give it a try, follow the guide, and you shouldn't have any problems. However, keep in mind that the SmartTerrain has certain limitations, especially concerning hardware and system requirements. You can find out more about the system in its documentation.

 6. VuMark

A VuMark is a kind of target that can be fully customized. It can reflect specific design choices or a brand personality. It's also extremely recognizable by the Vuforia tracking system, and it can start AR experiences or encode data.

Before you start to play around with VuMark, it's good to understand that the creation process isn't the simplest. The Vuforia team has put together a pretty good guide and some helpful tools, but I would recommend this solution only for specific situations where the design of the marker is of utmost importance.

I won't go into all the VuMark requirements and design processes. Instead, I'll just give you a general idea of the process and, if you decide to design your own VuMarker, you'll probably need to read Vuforia's guides first.

6.1 VuMark Design

It's vital to understand some architecture and design rules for VuMark, otherwise the target won't work properly.

A VuMark is composed of five parts:

Contour: The contour isn't actually drawn on the VuMark; it's defined by the contrast between the border and the clear space. It's the part that the Vuforia's algorithm first detects.

Border: The most identifiable and defining shape of the VuMark. It's made of straight lines, with at least four angles located at the outermost edge of the design.

Clear Space: A mandatory blank area that appears adjacent to the border. It guarantees there is enough contrast for the algorithm to detect the contour.

Code / Elements: The visual representation of the target's ID. This is composed of elements with high contrast, which represent two states, dark and light. The number of elements present is defined when creating the VuMark Template in Illustrator using the tools provided by Vuforia. (More on this in the next section.)

Background / Design Area: This area is a blank canvas that will be ignored by the algorithm. You can design freely on this space.

To find out more about the design requirements, read the VuMarkDesign Guide.

6.2 Creating a VuMark

 A VuMark is created using Adobe Illustrator and the VuMark Design Tools that are available for download on Vuforia's site. The tools are comprised of three Illustrator scripts, which come with some examples and a detailed PDF guide.

 Before starting a VuMark, you should design its concept, considering all the guidelines proposed by Vuforia. Once the design is complete, you'll start to break it down into parts, obeying VuMark's architecture.

 The first step is to create a new VuMark template, using the VuMark-Setup.jsx illustrated script. In the VuMark Template Setup window, you can choose the mark's name, ID type, and length. The number of characters encoded in the mark will define how many elements it must contain.

 Once the template is created, you must copy your design concept and break it down using the layers created by the script. Each layer represents an architectural part and has its own rule. You'll use the VuMark-Verify.jsx script to check if your design is correct. The script will give you advice on how to fix the design to conform to VuMark standards.

After breaking down your design and verifying that it conforms to VuMark standards, it's time to export the target. To export the design, you must run the VuMark-Export.jsx script. It will create a new file in Illustrator and move the contents from your VuMark template. It will then prompt you to save your VuMark template as an SVG file.

Finally, your marker will be ready, and you can upload the target file to a new database in Vuforia's Target Manager. Then you just need to download the database and use it like any other target.

 7. Exploring Other Cool Features

It's been a long journey into the Vuforia system and the possibilities for Augmented Reality. As you can see, the Vuforia system has a lot of cool features. This was my fifth post on Vuforia, and yet I still couldn't cover all its features. However, I'm confident that you have enough knowledge to explore those resources by yourself now.

Here are some pointers to other features that are worth exploring:

 User Defined Targets: works like ImageTarget, but the user can define the targets on the go using the device's camera.

 Cloud Recognition: exclusive to enterprise accounts. It's a kind of target database that lives in the cloud, allowing you to upload and synchronize new ImageTargets with the app on the fly.

 Object Recognition: This is an experimental feature that allows the recognition of an object, after it's been scanned using a special tool provided by Vuforia.

While you're here, check out some of our other posts on AR and mobile development!

Mobile Development

Create a Pokémon GO Style Augmented Reality Game With Vuforia

Tin Megali

Android SDK

Get Started With Android VR and Google Cardboard: Panoramic Images

Paul Trebilcox-Ruiz

Or to learn more about Augmented Reality with Vuforia and Unity, check out our video course here on Envato Tuts+!

Mobile App

Pokémon GO Style Augmented Reality: Markers

Derek Jensen

 2017-05-15T17:00:00.000Z 2017-05-15T17:00:00.000Z Tin Megali tag:gamedevelopment.tutsplus.com,2005:PostPresenter/cms-27992 Lighting in Unity 5

What You'll Be Creating

Unity has become more and more popular among aspiring game programmers. This is due to the fact that Unity directly supports a multitude of platforms such as mobile, desktop, and console environments. Moreover, it is free to use for lower revenue developers or studios.

Unity supports several technologies and components. Some of the key components are the lighting and illumination techniques. In Unity you can illuminate a scene by simulating the complex behaviour of lights or by applying a simple lighting model.

This tutorial will focus on explaining how lighting works in Unity 5, the lighting types and properties, and how to use them to create rich illumination effects.

 Prerequisites

First, ensure you have the latest version of Unity. In this tutorial we're using version 5.5.0f3. Make sure that you are using the latest Unity version; otherwise you may have problems following the tutorial and using the physics joints.

Next, download the LightingInUnity5-Starter file. Unzip and open the project in Unity. The Demo scene should open automatically, but if not, you can open it from the Assets folder.

Direct and Indirect Lighting

In a real-world scenario, you have two types of lighting effects: direct and indirect lighting. Direct lighting, as the name suggests, is light that comes directly from a light source (a lamp, the sun, or other). On the other hand, indirect lighting is light that comes from another object.

Let us test and implement both of them.

Direct lighting can already be seen in action in your Scene. As you probably noticed, you have a directional light in the scene called Directional Light.

Directional lights are mostly used in outdoor scenes for sun and moonlight. They affect all the surfaces of the objects in the scene. They are also the least expensive to the graphics processor.

You can select the Directional Light and view its properties in the Inspector pane. You will notice several interesting properties such as Type, Color, and Intensity. You can play with the Color and the Rotation properties and see the result in real time. By changing those values, you are directly playing with directional light.

At this moment, your 3D scene does not have any indirect light. You can check that by moving the Sphere closer to the green or red wall. The Sphere color will not change.

One way to use indirect lighting is to use static GameObjects. Keep in mind that the use of static game objects can improve the performance of your game rendering, but will also reduce the quality, so you must find the right balance for your game.

Add a box mesh box into your scene (GameObject > 3D Object > Cube), and place it next to the sphere. Name it Cube.

Select the Cube, and inside the Inspector enable the Static property.

When you enable the Static property, Unity automatically creates a light map for that object and applies the correct illumination model. You can now move the camera towards the Cube and see the indirect lighting working. The green (in the image) or the red color is now spreading into the Cube.

If you change the direction of the Directional Light, you will notice that Unity automatically updates the light maps as well.

The indirect lighting that is being applied to the Cube is not applied to the Sphere because the Sphere is not static. You can solve this by making the Sphere static (Inspector > Static).

At this moment, you can add and configure direct and indirect lighting to static objects. However, 3D scenes are composed of dynamic objects. Therefore, how can we apply such effects to those objects? That question leads us to the next section.

Light Probes

When your scene contains non-static objects, you need to use specific lighting techniques to correctly illuminate them so that they don't look disconnected from the scene.

Through the use of light probes and their positions, you can sample strategic points in the scene. Each light probe can sample a specific region and then calculate the lighting in that specific region. These calculations are fast enough to be used during gameplay. The use of light probes avoids any disconnect between the lighting of moving objects and static light-mapped objects in the scene.

The Sphere is a dynamic object, therefore, and contrary to what it may seem, it is not correctly illuminated. If you turn the Directional Light off, you will notice that the only lighting affecting the Sphere is the ambient light. To correctly illuminate the Sphere, you need to use light probes.

To add light probes to an area of your scene, you go to Component > Rendering > Light Probe Group. This will create a light probe group in your scene.

The next step is to put the probes of the group in the correct position. You now want to place them near each corner of the Box.

The best way to do this is to change to an orthographic view (by clicking on the cube on the upper right corner of the scene). Then, select each light probe node and drag it into each Box corner (similar to the next image).

Repeat the process until you have positioned all nodes.

There are scenes that require additional probes to correctly illuminate objects. In order to add more probes, you can select one probe and then under the Inspector, click on the Duplicate Selected button.

After the duplication, you need to place the new node in the right place (the duplicated one will spawn in the same position as the selected one).

If you take a closer look at the interface in the Inspector, you will notice that you can also add individual probes (Add Probe), delete probes (Delete Selected), or select all the probes from the group (Select All).

To see the light probes in action, select the Sphere and add a Rigidbody to it (Add Component > Rigidbody). Then, assign a material to the collider. You can use the rubber material.

Now, place the Sphere near the top of the Box and press Play. You can now see the proper illumination of the Sphere. To see the differences, disable the light probes and Play the scene again.

Point Light

Point lights are the most common light in games. They're usually used for explosions and light bulbs. Since they emit light in all directions, they have an average cost on the graphics processor. However, calculating shadows when using point lights is more expensive.

Add a point light by selecting GameObject > Light > Point Light. Next, position the Point light inside the Box near the top.

Select the Point light and take a look at the parameters in the Inspector.

The first parameter is Type. Here you can set the type of light you want to use. You can either select Spot, Directional, Point, or Area. Each provides a specific light effect. You can select any of the options and see the results in real time. However, for this tutorial you will use the Point option. This will create a light bulb effect (light shines in all directions equally).

The second parameter is Baking. You can set it to Realtime, Baked, or Mixed. Leave the value as default. The Range parameter defines how far the light is emitted from the center of the Point light. The Color parameter defines the emitted light color.

Intensity defines the brightness of the light, and Bounce Intensity defines the indirect light intensity multiplier. The Shadow Type defines the shadow properties and shadow types. You can either set it to No Shadows, Hard Shadows, or Soft Shadows. Remember that point light shadows are the most expensive for the engine, so be careful when selecting this option.

If you select Hard Shadows or Soft Shadows, you will see the shadow produced by the Sphere and the Point light. When you change the Strength value, the shadow will also attenuate or accentuate. The Resolution lets you define the detail level of the shadows. Finally, Bias and Normal Bias let you configure the offset used when comparing the pixel position in light space with the value from the shadow map.

The Cookie is an optional parameter that represents an alpha channel of a texture used as a mask that determines how bright the light is in different positions. Since this is a point light, the texture used must be a Cubemap.

The Draw Halo option only renders a halo around the light source. Flare defines a reference to a flare to be rendered at the light's position. Flare and Draw Halo can be useful when debugging the 3D scene and possible bottlenecks.

Render Mode defines how important lighting is when the renderer is rendering the scene. The more important, the more intensive the rendering will be. The Render Mode can be set to Auto, Important, or Non-Important. Finally, Culling Mask is used to select or exclude groups of objects that are affected by the point light.

Now that you've seen all the point light properties, let's talk about direct and indirect lighting when using point lights. When you create a game, one of the main characteristics is the use of lighting and illumination effects. However, a heavy lighting scenario will lead to heavier loading times, FPS bottlenecks, and more work for the CPU. Therefore, you are advised to play with Shadows Type and Baking properties to balance your scene performance.

For example, if you set the Baking to Realtime and the Shadow Type to Hard Shadows or Soft Shadows, you will have a very nice, realistic shadow effect between the Sphere and the Box. However, this setup can be heavy for the CPU if your scene is composed of many lights.

How to solve that issue? You can initially set the Baking parameter to Bake. Once you do this, Unity will automatically create lightmaps for this light, giving you a performance boost. However, this performance boost has its cost: now you don't have shadows being cast by the point light into dynamic objects, like the Sphere.

The best practice is to analyze each light individually, and then proceed accordingly. For example, in this scene it would make more sense to have Realtime Baking and Hard Shadows, because only one light source is present inside the box.

However, if your light source is a torch in a wall, it would be better to set Baking to Bake and let Unity produce the lightmaps.

Recall that it is up to the developer to manage the quality and performance of the game. Therefore, keep in mind that you have to be careful in keeping that balance, especially if you are developing for mobile devices.

Spot Light

Spot lights emit light from a light source targeting a specific region. They only illuminate objects within a specific region, a region delimited by a 3D cone. Basically, they work like the headlights of a car. As you may imagine, they are perfect for flashlights, car headlights, or lamp posts. They are also the most expensive light type for the graphics processor.

Let us now change the Point light into a spot light. Select the Point light you created earlier and change its Type to Spot. Next, Rotate the light so that it can illuminate the floor of the Box. Rename it to Spot light.

As you may have noticed, inside the Inspector, the Spot parameters are similar to the Point ones. However, you have a new one called Spot Angle.

The Spot Angle determines the angle of the light cone in degrees.

Regarding direct and indirect lighting, spot lights work exactly like point lights. You have the same limitations and advantages. Therefore, you have to be careful when setting up the balance of lights in your game.

Note that you can always play with shadows and baking in order to balance looks and performance.

Area Light

An area light is light is emitted in all directions on one side of a rectangular area of a plane. This rectangle is defined in both Width and Height properties. The area lights are only available during light map baking, which means that they have no effect on objects at runtime.

Select the Spot light and change its Type to Area and its name to Area light. Next, position the light inside your box, and in the Inspector, change the Width and the Height, in order to cover the whole area inside the Box.

By looking at the Area light parameters, you'll notice that most of the parameters are similar to the previous ones, for example Type, Draw Halo, Flare, Render Mode, and Culling Mask.

The real new parameters are the Width and Height. Both are used to set the size of the rectangular light area.

If you press Play, you will see that the area light is casting its light on all objects within its range. The size of the rectangle is determined by the Width and Height properties. The side on which light is being cast is the plane's normal, which is the same as the light's positive Z direction. The light is emitted from the whole surface of the rectangle. Because of this, shading and shadows from the affected object tend to be much softer than with point or directional light sources.

The lighting calculations for an area light are quite processor-intensive, so they are not available at runtime and can only be Baked into light maps.

Conclusions

This concludes the tutorial about lighting in Unity 5. You learned about several lighting effects and configurations. With this knowledge, you can now apply several lighting effects to your game or application.

Unity has an active economy. There are many other products that help you build out your project. The nature of the platform also makes it a great option from which you can better your skills. Whatever the case, you can see everything we have available in the Envato Marketplace.

If you have further questions or comments, as always, feel free to drop a line in the comments section.
 2017-01-24T13:00:37.000Z 2017-01-24T13:00:37.000Z Orlando Pereira and Pedro Pereira tag:gamedevelopment.tutsplus.com,2005:PostPresenter/cms-26363 How to Build a Prince-of-Persia-Style Time-Rewind System, Part 2

What You'll Be Creating

Last time we created a simple game where we can rewind the time to a previous point. Now we will solidify this feature and make it much more fun to use.

Everything we do here will build on the previous part, so go check it out! As before, you will need Unity and a basic understanding of it.

Ready? Let's go!

Record Less Data and Interpolate

Right now we record the positions and rotations of the player 50 times a second. This amount of data will quickly become untenable, and this will become especially noticeable with more complex game setups and mobile devices with less processing power.

But what we can do instead is only record 4 times a second and interpolate between those keyframes. That way we save 92% of the processing bandwidth, and get results that are indistinguishable from the 50-frame recordings, as they play out within fractions of a second.

We'll start by only recording a keyframe every x frames. To do this, we first need these new variables:

public int keyframe = 5; private int frameCounter = 0;

The variable keyframe is the frame in the FixedUpdate method at which we will record the player data. Currently, it is set to 5, which means every fifth time the FixedUpdate method cycles through, the data will be recorded. As FixedUpdate runs 50 times per second, this means 10 frames will be recorded per second, compared to 50 before. The variable frameCounter will be used to count the frames until the next keyframe.

Now adapt the recording block in the FixedUpdate function to look like this:

if(!isReversing) { if(frameCounter < keyframe) { frameCounter += 1; } else { frameCounter = 0; playerPositions.Add (player.transform.position); playerRotations.Add (player.transform.localEulerAngles); } }

If you try it out now, you will see that the rewinding takes part in a much shorter time than before. This is because we recorded less data, but played it back at regular speed. Now we need to change that.

First, we need another frameCounter variable to keep track not of recording the data, but of playing it back.

private int reverseCounter = 0;

Adapt the code that restores the player's position to utilize this the same way we record the data. The FixedUpdate function should then look like this:

void FixedUpdate() { if(!isReversing) { if(frameCounter < keyframe) { frameCounter += 1; } else { frameCounter = 0; playerPositions.Add (player.transform.position); playerRotations.Add (player.transform.localEulerAngles); } } else { if(reverseCounter > 0) { reverseCounter -= 1; } else { player.transform.position = (Vector3) playerPositions[playerPositions.Count - 1]; playerPositions.RemoveAt(playerPositions.Count - 1); player.transform.localEulerAngles = (Vector3) playerRotations[playerRotations.Count - 1]; playerRotations.RemoveAt(playerRotations.Count - 1); reverseCounter = keyframe; } } }

When you rewind time now, the player will jump back to their previous positions, in real time!

That's not quite what we want, though. We need to interpolate between those keyframes, which will be a bit trickier. First, we need these four variables:

private Vector3 currentPosition; private Vector3 previousPosition; private Vector3 currentRotation; private Vector3 previousRotation;

Those will save the current player data and the one from the recorded keyframe before that so that we can interpolate between those two.

Then we need this function:

void RestorePositions() { int lastIndex = keyframes.Count - 1; int secondToLastIndex = keyframes.Count - 2; if(secondToLastIndex >= 0) { currentPosition = (Vector3) playerPositions[lastIndex]; previousPosition = (Vector3) playerPositions[secondToLastIndex]; playerPositions.RemoveAt(lastIndex); currentRotation = (Vector3) playerRotations[lastIndex]; previousRotation = (Vector3) playerRotations[secondToLastIndex]; playerRotations.RemoveAt(lastIndex); } }

This will assign the corresponding information to the position and rotation variables which we will interpolate between. We need this in a separate function, as we call it in two different spots.

Our data-restoring block should look like this:

if(reverseCounter > 0) { reverseCounter -= 1; } else { reverseCounter = keyframe; RestorePositions(); } if(firstRun) { firstRun = false; RestorePositions(); } float interpolation = (float) reverseCounter / (float) keyframe; player.transform.position = Vector3.Lerp(previousPosition, currentPosition, interpolation); player.transform.localEulerAngles = Vector3.Lerp(previousRotation, currentRotation, interpolation);

We call the function to get the last and second to last information sets from our arrays whenever the counter reaches the keyframe interval we have set (in our case 5), but we also need to call it on the first cycle when the restoring is happening. This is why we have this block:

if(firstRun) { firstRun = false; RestorePositions(); }

In order for this to work, you also need the firstRun variable:

private bool firstRun = true;

And to reset it when the space button is lifted:

if(Input.GetKey(KeyCode.Space)) { isReversing = true; } else { isReversing = false; firstRun = true; }

Here is how the interpolation works:

Instead of just using the last keyframe we saved, this system gets the last and the second-to-last and interpolates between them. The amount of interpolation is based on how far between the frames we currently are.

This all happens via the Lerp function, where we add the current position (or rotation) and the previous one. Then the fraction of the interpolation is calculated, which can go from 0 to 1. Then the player is placed at the equivalent place between those two saved points, for example, 40% on the route to the last keyframe.

When you slow it down and play it frame by frame, you can actually see the player-character move between those keyframes, but in gameplay, it's not noticeable.

And thus we have greatly reduced the complexity of the time-rewinding setup and made it much more stable.

Only Record a Fixed Number of Keyframes

Now that we have greatly reduced the number of frames we actually save, we can make sure we don't save too much data.

Right now we just pile the recorded data into the array, which will not do long-term. As the array grows, it will become more unwieldy, access will take longer amounts of time, and the entire setup will become more unstable.

In order to fix this, we can institute code that checks if the array has grown over a certain size. If we know how many frames per second we save, we can determine how many seconds of rewindable time we should save, and what would fit our game and its complexity. The somewhat complex Prince of Persia allows for maybe 15 seconds of rewindable time, while the simpler setup of Braid allows for unlimited rewinding.

if(playerPositions.Count > 128) { playerPositions.RemoveAt(0); playerRotations.RemoveAt(0); }

What happens is that once the array grows over a certain size, we remove the first entry of it. Thus it only stays as long as we want the player to rewind, and there is no danger of it becoming too large to use efficiently. Put this in the FixedUpdate function after the recording and replaying code.

Use a Custom Class to Hold Player Data

Right now we record the player positions and rotations into two separate arrays. While this does work, we have to remember to always record and access the data in two places at the same time, which has the potential for future problems.

What we can do, however. is create a separate class to hold both of these things, and possibly even more (if that should be necessary in your project).

The code for a custom class to act as container for the data looks like this:

public class Keyframe { public Vector3 position; public Vector3 rotation; public Keyframe(Vector3 position, Vector3 rotation) { this.position = position; this.rotation = rotation; } }

You can add it to the TimeController.cs file, right before the class declaration starts. What it does is provide a container to save both the position and rotation of the player. The constructor method allows it to be directly created with the necessary information.

The rest of the algorithm will need to be adapted to work with the new system. In the Start method, the array needs to be initialized:

keyframes = new ArrayList();

And instead of saying:

playerPositions.Add (player.transform.position); playerRotations.Add (player.transform.localEulerAngles);

We can save it directly into a Keyframe object:

keyframes.Add(new Keyframe(player.transform.position, player.transform.localEulerAngles));

What we do here is add the position and rotation of the player into the same object, which then gets added into a single array, which greatly reduces the complexity of this setup.

Add a Blurring Effect to Signify That Rewinding Is Happening

We drastically need some kind of signifier telling us the game is currently being rewound. Right now, we know this, but a player might be confused. In such situations it is good to have multiple things telling the player that rewinding is happening, like visually (via the entire screen blurring a bit) and audio (by the music slowing down and reversing).

Let's do something similar to how Prince of Persia does it, and add some blurring.

Time-rewinding from Prince of Persia: The Forgotten Sands

Unity allows you to add multiple camera effects on top of each other, and with some experimenting you can make one that fits your project perfectly.

Before we can use the basic effects, we need to import them. To do this, go to Assets > Import Package > Effects, and import everything that is offered to you.

Visual effects can be added directly to the main camera. Go to Components > Image Effects and add a Blur and a Bloom effect. The combination of those two should provide a nice effect for what we are going for.

These are the basic settings. You can adjust them to better suit your project.

When you try it out now, the game will have this effect on all the time.

Now we need to activate it and deactivate it respectively. For that, the TimeController needs to import the image effects. Add this line to the very beginning:

using UnityStandardAssets.ImageEffects;

To access the camera from the TimeController, add this variable:

private Camera camera;

And assign it in the Start function:

camera = Camera.main;

Then add this code to activate the effects while rewinding time, and have them activated otherwise:

void Update() { if(Input.GetKey(KeyCode.Space)) { isReversing = true; camera.GetComponent<Blur>().enabled = true; camera.GetComponent<Bloom>().enabled = true; } else { isReversing = false; firstRun = true; camera.GetComponent<Blur>().enabled = false; camera.GetComponent<Bloom>().enabled = false; } }

When you press the space button, you now not only rewind the scene, but you also activate the rewind effect on the camera, telling the player that something is happening.

The entire code of the TimeController should look like this:

using UnityEngine; using System.Collections; using UnityStandardAssets.ImageEffects; public class Keyframe { public Vector3 position; public Vector3 rotation; public Keyframe(Vector3 position, Vector3 rotation) { this.position = position; this.rotation = rotation; } } public class TimeController: MonoBehaviour { public GameObject player; public ArrayList keyframes; public bool isReversing = false; public int keyframe = 5; private int frameCounter = 0; private int reverseCounter = 0; private Vector3 currentPosition; private Vector3 previousPosition; private Vector3 currentRotation; private Vector3 previousRotation; private Camera camera; private bool firstRun = true; void Start() { keyframes = new ArrayList(); camera = Camera.main; } void Update() { if(Input.GetKey(KeyCode.Space)) { isReversing = true; camera.GetComponent<Blur>().enabled = true; camera.GetComponent<Bloom>().enabled = true; } else { isReversing = false; firstRun = true; camera.GetComponent<Blur>().enabled = false; camera.GetComponent<Bloom>().enabled = false; } } void FixedUpdate() { if(!isReversing) { if(frameCounter < keyframe) { frameCounter += 1; } else { frameCounter = 0; keyframes.Add(new Keyframe(player.transform.position, player.transform.localEulerAngles)); } } else { if(reverseCounter > 0) { reverseCounter -= 1; } else { reverseCounter = keyframe; RestorePositions(); } if(firstRun) { firstRun = false; RestorePositions(); } float interpolation = (float) reverseCounter / (float) keyframe; player.transform.position = Vector3.Lerp(previousPosition, currentPosition, interpolation); player.transform.localEulerAngles = Vector3.Lerp(previousRotation, currentRotation, interpolation); } if(keyframes.Count > 128) { keyframes.RemoveAt(0); } } void RestorePositions() { int lastIndex = keyframes.Count - 1; int secondToLastIndex = keyframes.Count - 2; if(secondToLastIndex >= 0) { currentPosition = (keyframes[lastIndex] as Keyframe).position; previousPosition = (keyframes[secondToLastIndex] as Keyframe).position; currentRotation = (keyframes[lastIndex] as Keyframe).rotation; previousRotation = (keyframes[secondToLastIndex] as Keyframe).rotation; keyframes.RemoveAt(lastIndex); } } }

Download the attached build package and try it out!

Conclusion

Our time-rewind game is now much better than before. The algorithm is noticeably improved and uses 90% less processing power, it is much more stable, and we have a nice signifier telling us that we are currently rewinding time.

Now go make a game using this!
 2016-09-13T14:00:25.000Z 2016-09-13T14:00:25.000Z Matthias Zarzecki tag:gamedevelopment.tutsplus.com,2005:PostPresenter/cms-27160 Pokémon GO Style Augmented Reality With Vuforia
 1. Introduction

Thanks to the wild success of Pokémon GO, augmented reality (AR) is getting a lot of attention in the mobile development world. The idea of augmented reality isn't new, but only now is the technology finally getting close to maturity and commercial viability. But what is augmented reality exactly?

This a really broad concept that can take many different forms. The idea can be applied to entertainment, science, military, education, you name it. What these applications all have in common, though, is a real-time connection between the physical world and the digital.

A live direct or indirect view of a physical, real-world environment whose elements are augmented (or supplemented) by computer-generated sensory input such as sound, video, graphics or GPS data. — Wikipedia

Concretely, AR is often realized in interactive experiences that overlay a camera feed with 2D or 3D objects, informed by some sensor data.

However, creating an engaging augmented reality experience from scratch can be a real challenge. Fortunately, there are some solutions available that can make this job easier. One of the most solid augmented reality tools out there is Vuforia, an AR library that is compatible with Android, iOS, UWP, and some brands of smart glasses.

In this tutorial we'll explore augmented reality using Vuforia. We'll explore Vuforia's features, possibilities, and challenges, and we'll also take a look at how the SDK works and its main functions. We won't explore any code in this tutorial—future tutorials in this series will dig into coding in Vuforia, with step-by-step guides targeting all the library's main features.

If you want to dig deeper, why not learn about one of the most fundamental of concepts of AR, markers, in our short course:

Mobile App

Pokémon GO Style Augmented Reality: Markers

Derek Jensen

 2. Vuforia

Originally developed by Qualcomm and recently bought by PTC, Vuforia is on its sixth version. Its SDK is constantly evolving and is compatible with Android, iOS, UWP, and Unity. Unfortunately, Vuforia isn't open source, but its price range is reasonable, and there is no up-front cost for development or education. You can create almost any kind of AR experience on the most popular mobile platforms using Vuforia.

2.1. How Does It Work?

Vuforia uses the device's camera feed combined with accelerometer and gyroscope data to examine the world. Vuforia uses computer vision to understand what it 'sees' on the camera to create a model of the environment. After processing the data, the system can roughly locate itself in the world, knowing its coordinates: where is up, down, left, right, and so on. What you do with this depends on your development goals.

There are multiple possibilities:

 Using World coordinates: Any kind of object can be exhibited using some arbitrary reference, ignoring real obstacles but considering the World localization obtained. The object can be out of view and continue to "exist" in the same position. This is a system similar to the one used by Pokémon GO.

 Recognizing targets: Vuforia can look for specific images as "targets". VuMarks, for example, a QR code-style image highly recognizable by the system, can be used as anchor points or references for any kind of object projected into the world. A magazine could be 'expanded' with this resource, with its pages opening rich interactions like videos, audio, and so on.

 Recognizing simple objects: Simple objects like boxes and cylinders can be recognized and used as anchor points. This method is useful for recognizing packages and making them interactive.

 Recognizing complex objects: Vuforia can also look for complex objects, like toys, computer parts, gadgets, and so on. Those objects are previously scanned, conforming to specific requirements, and can later be recognized by the system. This functionality could be used, for example, to turn toys into live creatures, or to create interactive assistance for mechanics or service people.

 Looking for words: English words can also be understood by Vuforia. The system can look for specific words and target some kind of interaction on them. This could be useful for learning tools for children or for language translation.

 Recognizing the world's terrain: One of the most powerful features available on Vuforia is the ability to recognize the world as it is. Vuforia lets the user scan their surroundings and can do some hardcore processing to interpret the world by creating a 3D computer vision of the real world and its objects. Imagine a Pokémon GO-like game where the Pokémons can hide behind real objects. Wouldn't that be awesome?

2.2. Developing With Vuforia

Vuforia is compatible with multiple systems. Its software development kits (SDKs) are available for Android, iOS, UWP, and Unity. Once you download and install the SDK, you'll need to sign up for a developer account and create an app key before you can start to code.

Even though Vuforia is compatible with many systems, the easiest way to create engaging AR experiences using its SDK is definitely using Unity. Don't get me wrong, you can access almost everything that Vuforia offers when developing directly for Android or iOS. However, the process is much simpler when done using the prefabs offered on Vuforia's SDK for Unity.

 3. Vuforia Targets

As mentioned before, Vuforia can seek 'targets' on the camera feed to create anchor points or references to be used by AR experiences. Those targets can assume many forms, and any file that has been previously processed by Vuforia target manager can be recognized. Targets can be created by the developer or created during execution by the user.

 3.1

3.1. Image Targets

Any kind of image can be a Vuforia Image Target. However, the more detailed and intricate the image, the better it is to be recognized by the algorithm. A lot of factors will be part of the recognizing calculation, but basically the image must have a reasonable level of contrast, resolution, and distinguishing elements. A blue sky photograph wouldn't work very well, but a picture of some grass would work gracefully. Image Targets can be shipped with the application, created later and uploaded to the application through a cloud system, or directly created on the app by the user.

3.2. VuMarks

A VuMark works very similarly to a QR Code; however, it's much more versatile. It can assume many shapes and colors and adapt to a great number of environments. Its biggest advantage is that it's in total conformity with Vuforia's recognizing algorithm and will be easily 'found' by any Vuforia AR application. Vuforia also offers an Adobe Illustrator plugin that creates VuMarks.

3.3. Cylinder and Cube Targets

It's also possible to use cubes and cylinders as Image Targets. This is very appropriate to create engagement with product packages. Once recognized, the primitive object is used as an anchor point, and it seems to exist for the system's computer vision, allowing virtual objects to interact directly with the primitive. The virtual object could track the real object's position and orientation, for example.

3.4. Objects as Targets

One of the most interesting features of Vuforia is the possibility to recognize complex objects. A toy, a phone, a computer board, and other kinds of objects can be used as targets.

To use this resource, you have to scan the object using the Vuforia Object Scanner tool, which runs only on Samsung Galaxy S6 and S7. The data scan is uploaded to Vuforia Target Manager, and the scanned object will be recognized by any compatible device using that data.

3.5. Managing Targets

There are multiple ways to create a target:

The application can ship with a series of targets embedded.

The app can receive targets online through the cloud system offered by Vuforia.

The user themselves can use the device's camera to create a target.

As a developer, you don't have much control about how the user will create their target; all that you can do is provide the user with some tips about how to chose an appropriate image as a target. However, the situation is different for the targets processed using the Target Manager.

Vuforia's developer portal provides us with the Target Manager tool to help manage all our apps' targets. The manager is very simple to use: you create a database to hold the targets, upload a file that corresponds to a target, and wait until the file is processed. The target will receive a unique ID and a score related to how recognizable it is and will then become part of the database, available for download or for storage in the cloud.

There are three different types of target databases:

 Device Databases are local databases of images or object targets that are stored on the user's device.

 VuMark Databases are local databases of VuMarks that are stored on the user's device.

 Cloud Databases are databases of Image Targets stored online and queried over the internet.

 4. Smart Terrain

When developing a Vuforia app on Unity, there is a really exciting option available, the Smart Terrain. It allows an application to replicate 3D meshes of objects seen by the camera.

The process works like some kind of scan, where the user uses the device's camera as a 3D scanner. As the camera scans through the ambient environment, the application creates 3D models of the recognized objects, giving the application the possibility to adjust the scenario to the real world, creating a deeply engaging experience.

 5. Conclusion

There are hundreds of possibilities to explore with augmented reality, and we're just starting to scratch its surface. Many believe that AR will be a part of our future and that we'll use it on a day-to-day basis. This is a field that promises to grow a lot in the coming years, and Vuforia provides us with cool tools to create engaging experiences.

5.1 What's Next

In the following tutorials of this series, we'll work with some of Vuforia's most important tools. We'll develop a lot of small experiments to illustrate the SDK capabilities, and since Unity is the most AR-friendly environment available, everything will be developed on it.

It won't be necessary to be a Unity expert to follow the tutorials—since our focus is the Vuforia SDK, I'll provide you with step-by-step guides that require only minimal previous experience with Unity.

If you want to learn a little more about Unity in the meantime, check out some of our other tutorials.

Create a Basketball Free Throw Game with Unity

In this tutorial, you'll create a basketball free throw game in Unity. You'll learn about 3D models, mesh colliders, physics materials, collision detection,...

 <address class="posts__post-author">Carlos Yanez</address> <time class="posts__post-publication-date" datetime="2014-06-27 15:39:13 UTC" title="27 Jun 2014">27 Jun 2014</time>

Mobile Development

Creating a 3D City in Unity 5

Welcome to our Unity tutorial where we will create a 3D city in the Unity 5 game engine. You can use this project for your first-person or third-person...

 <address class="posts__post-author">Sandra Gerber</address> <time class="posts__post-publication-date" datetime="2016-05-19 13:00:47 UTC" title="19 May 2016">19 May 2016</time>

Unity 3D

Text Input for Games With Just an Intel RealSense Camera

In this post, I'll share what I've learned about the best (and worst!) ways to let players enter text via gesture alone, and show you how to set up the Intel...

 <address class="posts__post-author">Chris Skaggs</address> <time class="posts__post-publication-date" datetime="2016-01-28 16:05:41 UTC" title="28 Jan 2016">28 Jan 2016</time>

Intel RealSense

See you soon!
 2016-09-12T12:01:07.000Z 2016-09-12T12:01:07.000Z Tin Megali tag:gamedevelopment.tutsplus.com,2005:PostPresenter/cms-26090 How to Build a Prince-of-Persia-Style Time-Rewind System, Part 1

What You'll Be Creating

In this tutorial, we'll build a simple game where the player can rewind progress in Unity (it can also be adapted to work in other systems). This first part will go into the basics of the system, and the next part will flesh it out and make it much more versatile.

First, though we'll take a look at what games use this. Then we'll look at the other uses for this technical setup, before ultimately creating a small game that we can rewind, which should give you a basis for your own.

A demonstation of the basic functionality

You will need the newest version of Unity for this, and should have some experience with it. The source code is also available for download if you want to check your own progress against it.

Ready? Let's go!

How Has This Been Used Before?

Prince of Persia: The Sands of Time is one of the first games to truly integrate a time-rewinding mechanic into its gameplay. When you die you do not just have to reload, but can rather rewind the game for a few seconds to where you were alive again, and immediately try again.

Prince of Persia: The Forgotten Sands. The Sands Of Time Trilogy integrates time-rewinding beautifully into its gameplay and avoids immersion-breaking quick-reloading.

This mechanic is not only integrated into the gameplay, but the narrative and universe as well, and is mentioned throughout the story.

Other games that employ these systems are Braid, for example, which is also centered around the winding of time. The hero Tracer in Overwatch has a power that resets her to a position a few seconds ago, essentially rewinding her time, even in a multiplayer game. The GRID-series of racing games also has a snapshot-mechanic, where you have a small pool of rewinds during a race, which you can access when you have a critical crash. This prevents frustration caused by crashes near the end of race, which can be especially infuriating.

When you have a fatal crash in GRID you get the chance to rewind the game to a point before the crash.

Other Uses

But this system can not only be used to replace quick-saving. Another way this is employed is ghosting in racing games and asynchronous multiplayer.

Replays

Replays are another fun way to employ this feature. This can be seen in games like SUPERHOT, the Worms series, and pretty much the majority of sports games.

Sports-replays work the same way they are presented on TV, where an action is showed again, possibly from a different angle. For this not a video is recorded but rather the actions of the user, allowing the replay to employ different camera angles and shots. The Worms games use this in a humorous way, where very comical or effective kills are shown in an Instant Replay.

SUPERHOT also records your movement. When you are done playing around your entire progress is then replayed, showing the few seconds of actual movement that happened.

Super Meat Boy uses this in a fun way. When you finish a level you see a replay of all your previous attempts laid on top of each other, culminating with your finishing run being the last left standing.

The end-of-level replay in Super Meat Boy. Every one of your previous attempts is recorded and then played back at the same time.

Time-Trial Ghosts

Race-Ghosting is a technique where you race for the best time on an empty track. But at the same time, you race against a ghost, which is a ghostly, transparent car, which drives the exact way you raced before on your best attempt. You cannot collide with it, which means you can still concentrate on getting the best time.

Instead of driving alone you get to compete against yourself, which makes time-trials much more fun. This feature shows up in the majority of racing games, from the Need for Speed series to Diddy Kong Racing.

Racing a ghost in Trackmania Nations. This one has the silver difficulty, meaning I will get the silver medal if I beat them. Note the overlap in car-models, showing the ghost isn't corporeal and can be driven through.

Multiplayer-Ghosts

Asynchronous Multiplayer-Ghosting is another way to use this setup. In this rarely-used feature, multiplayer matches are accomplished by recording the data of one player, who then sends their run to another player, who can subsequently battle against the first player. The data is applied the same way a time-trial-ghost would be, only that you are racing against another player.

A form of this shows up in the Trackmania-games, where it is possible to race against certain difficulties. These recorded racers will give you an opponent to beat for a certain reward.

Movie-Editing

Few games offer this from the get-go but used right it can be a fun tool.Team Fortress 2 offers a built-in replay-editor, with which you can create your own clips.

The replay editor from Team Fortress 2. Once recorded a match can be seen from any perspective, not just the player's.

Once the feature has been activated you can record and watch previous matches. The vital element is that everything is recorded, not only your view. This means you can move around the recorded game-world, see where everyone is, and have control over time.

How to Build It

In order to test this system, we need a simple game where we can test it. Let's create one!

The Player

Create a cube in your scene, this will be our player-character. Then create a new C#-script calls Player.cs and adapt the Update()-function to look like this:

void Update() { transform.Translate (Vector3.forward * 3.0f * Time.deltaTime * Input.GetAxis ("Vertical")); transform.Rotate (Vector3.up * 200.0f * Time.deltaTime * Input.GetAxis ("Horizontal")); }

This will handle simple movement via the arrow keys. Attach this script to the player cube. When you now hit play you should already be able to move around.

Then angle the camera so that it views the cube from above, with room on its side where we can move it. Lastly, create a plane to act as floor and assign some different materials to each object, so that we're not moving it inside of a void. It should look like this:

Try it out, and you should be able to move your cube using the WSAD and arrow-keys.

The TimeController

Now create a new C#-script called TimeController.cs and add it to a new empty GameObject. This will handle the actual recording and subsequent rewinding of the game.

In order to make this work, we will record the movement of the player character. When we then press the rewind button we will adapt the player coordinates. To do so start by creating a variable to hold the player, like this:

public GameObject player;

And assign the player-object to the resulting slot on the TimeController, so that it can access the player and its data.

Then we need to create an array to hold the player data:

public ArrayList playerPositions; void Start() { playerPositions = new ArrayList(); }

What we will do next is continuously record the position of the player. We will have the position stored of where the player was in the last frame, the position where the player was 6 frames ago, and the position where the player was 8 seconds ago (or however long you will set it to record). When we later hit a button we'll go backward through our array of positions and assign it frame by frame, resulting in a time-rewinding feature.

First, let's save the data:

void FixedUpdate() { playerPositions.Add (player.transform.position); }

In the FixedUpdate()-function we record the data. FixedUpdate() is used as it runs at a constant 50 cycles per second (or whatever you set it to), which allows for a fixed interval to record and set the data. The Update()-function meanwhile runs depending on how many frames the CPU manages, which would make things more difficult.

This code will store the player-position of each frame in the array. Now we need to apply it!

We'll add a check to see if the rewind button was pressed. For this, we need a boolean variable:

public bool isReversing = false;

And a check in the Update()-function to set it according to whether we want to rewind the gameplay:

void Update() { if(Input.GetKey(KeyCode.Space)) { isReversing = true; } else { isReversing = false; } }

To make the game run backward, we will apply the data instead of recording. The new code for recording and applying of the player position should look like this:

void FixedUpdate() { if(!isReversing) { playerPositions.Add (player.transform.position); } else { player.transform.position = (Vector3) playerPositions[playerPositions.Count - 1]; playerPositions.RemoveAt(playerPositions.Count - 1); } }

And the entire TimeController-script like this:

using UnityEngine; using System.Collections; public class TimeController: MonoBehaviour { public GameObject player; public ArrayList playerPositions; public bool isReversing = false; void Start() { playerPositions = new ArrayList(); } void Update() { if(Input.GetKey(KeyCode.Space)) { isReversing = true; } else { isReversing = false; } } void FixedUpdate() { if(!isReversing) { playerPositions.Add (player.transform.position); } else { player.transform.position = (Vector3) playerPositions[playerPositions.Count - 1]; playerPositions.RemoveAt(playerPositions.Count - 1); } } }

Also, don't forget to add a check to the player-class to see if the TimeController is currently rewinding or not, and only move when it is not reversing. Otherwise, it might create buggy behavior:

using UnityEngine; using System.Collections; public class Player: MonoBehaviour { private TimeController timeController; void Start() { timeController = FindObjectOfType(typeof(TimeController)) as TimeController; } void Update() { if(!timeController.isReversing) { transform.Translate (Vector3.forward * 3.0f * Time.deltaTime * Input.GetAxis ("Vertical")); transform.Rotate (Vector3.up * 200.0f * Time.deltaTime * Input.GetAxis ("Horizontal")); } } }

These new lines will automatically find the TimeController-object in the scene on startup and check it during runtime to see if we are currently playing the game or rewinding it. We can only control the character when we are currently not reversing time.

Now you should be able to move around the world, and rewind your movement by pressing space. If you download the build package attached to this article and open TimeRewindingFunctionality01 you can try it out!

But wait, why does our simple player-cube keep looking in the last direction we left them in? Because we didn't get around to also record its rotation!

For that you need another array to keep its rotation-values, to instantiate it at the beginning, and to save and apply the data the same way we handled position-data.

using UnityEngine; using System.Collections; public class TimeController: MonoBehaviour { public GameObject player; public ArrayList playerPositions; public ArrayList playerRotations; public bool isReversing = false; void Start() { playerPositions = new ArrayList(); playerRotations = new ArrayList(); } void Update() { if(Input.GetKey(KeyCode.Space)) { isReversing = true; } else { isReversing = false; } } void FixedUpdate() { if(!isReversing) { playerPositions.Add (player.transform.position); playerRotations.Add (player.transform.localEulerAngles); } else { player.transform.position = (Vector3) playerPositions[playerPositions.Count - 1]; playerPositions.RemoveAt(playerPositions.Count - 1); player.transform.localEulerAngles = (Vector3) playerRotations[playerRotations.Count - 1]; playerRotations.RemoveAt(playerRotations.Count - 1); } } }

Try it out! TimeRewindingFunctionality02 is the improved version. Now our player-cube can move backward in time, and will look the same way it did when it was at that moment.

Conclusion

We have built a simple prototype game with an already usable time-rewinding system, but it is far from done yet. In the next part of this series we'll make it much more stable and versatile, and add some neat effects.

Here is what we still need to do:

Only record every ~12th frame and interpolate between the recorded ones to save on the huge data load

Only record the last ~75 player positions and rotations to make sure the array doesn't become too unwieldy and the game doesn't crash

We'll also take a look at how to extend this system past just the player-character:

Record more than just the player

Add an effect to signify rewinding is happening (like VHS-blurring)

Use a custom class to hold player position and rotation instead of arrays

 2016-06-24T12:00:05.000Z 2016-06-24T12:00:05.000Z Matthias Zarzecki