Showing posts with label Unity3d. Show all posts
Showing posts with label Unity3d. Show all posts

Wednesday, 18 November 2015

Low-poly water on UE4

Note: For some reason, the original videos disappeared from blogger and I've had to create new ones.


Here's how to achieve a cool retro-style water effect using UE4

First of all, we need a suitable plane. While Unreal comes with one we can use straight out of the box, I prefer having one that's just right for my purposes. Here's one I made using Blender.

The UV map (to the left) is rather important to get right, or you'll just get wonky results. Make sure it maps the corners to 0,0 and 1,1.
And because I know you're in a hurry, here's the final shader (you can copy and paste this into an empty material to save you a lot of work):

How it works:

Firstly we take the current time and use it as UV coordinate modifiers to sample a nice, smooth and tiled noise texture. I found "LowResBlurredNoise" (make sure you're allowed to view engine assets in order to select it) perfect.


To avoid most issues with occlusion culling I then "normalize" the values between -0,5 and 0,5. Why is this important? It allows us to increase and decrease the vertices' height relative to their original position rather than just adding to it (and thus always skewing them upwards). You could multiply this by 2 to make the values range from -1 to 1 but you can achieve the same thing by tweaking the wave scale value.

Finally, with a suitable noise map, all we have to do it modify the original vertex position. We take the normal (which would point up in the case of your plane), multiply it by the noise values and as time pans the noise texture forward through all the vertices in our plane, we get a wave.


Why use the vertex normal instead of just a global "up vector" (like 0,0,1)? It allows us to place water sideways and so some weird stuff with other shapes, like this:



The bits connected to the "normal" part of the material are a bit of "dark math magic" which recalculates the vertex normals after we modify their position. If it wasn't there, the lighting on our water would be constant and look completely hideous. I may go into more detail on this one day.

Usage Notes:

  • You CAN put several of these planes beside each other. They will cleanly fit and should have no seams if you've done the uv mapping properly.
  • As with all vertex-deforming materials, this one will become a bit iffy with occlusion culling, especially with huge "Wave Height Scale" values.
  • Make sure the water plane isn't casting shadows on itself or is otherwise baked by Lightmass
  • Keep in mind that due to oscillating height, it may clip through the ground if you're not careful.
  • Unfortunately, due to the way Unreal handles flat shading, this leaves us with a rather high poly count for a simple flat shaded plane. But this has nothing to do with the Water Material itself.


Addendum: If you're into Unity3D, /u/Ro9AM has posted a neat little tutorial (with source code) that does pretty much the same thing :)

Thursday, 10 September 2015

On moving from Unity to Unreal

The team at Titan is working on a soon-to-be-announced Top Secret Project. We've recently changed from Unity to Unreal and here are some things we've thought about sharing with other Devs that are thinking of making the jump.


The good stuff: 

  • Unreal let's you easily alter the aesthetics of your project. The drag and drop material editor, the huge amounts of built-in high quality content let you easily reach AAA levels of quality, even for small prototypes.
  • Blueprints are amazing for quickly prototyping concepts! Beware: any non-trivial math expressions will be a mess of wires, but thankfully there's a handy math expression node to help you avoid turning your code into a spaghetti mess.
  • The community has a lot of experienced developers, which makes useful content and non-trivial tutorials easier to find.
  • The architecture and the way everything is structured encourages newbie developers to write more robust code. Contrary to Unity, there's already a game state, game modes, an Actor-Controller model...
  • Epic's experience has led to so much high quality content that you can easily pick up something like the FPS Tutorial and merely have to tweak a few values to suit your needs - We recreated the movement style of our first Unity game (Slinki) in a matter of minutes.

The bad stuff:

  • The render pipeline is setup for realistic lighting, if you want something really stylistic illumination you can either "hack" your way around this with more complex materials or get down and dirty with the rendering pipeline.
  • Don't get me wrong, Unity can be a bit of a resource hog sometimes. But Unreal seems to be an expert at making even our reasonable Gaming PCs suffer. Compile times will be measured in minutes for anything but the smallest projects.
  • The way Unreal handles project files is simply not as robust as Unity's. Every time you move something, a file a redirector is created. 
  • You can't just drop a png file and use it as an asset, there's always going to be some sort of pipeline to get assets into your game. 
  • As a sidenote to the previous point, you will have to export your blender models as an fbx. Many things can and will go wrong with this process. I would write a tutorial but I found it changes a lot between versions of both programs and none of our solutions have been ideal so far.
  • C# is gone. You will be using C++. This can be a curse or a blessing but overall C++ is not as great for quickly prototyping.
  • It's not very stable. Seriously, it's not. The update to 4.9 broke transparent sprites on the UI. This is not a trivial and easily-ignored bug.
  • The huge ingress of novice game developers has made communication with the Epic team and experienced members slightly harder due to a sea of (mostly) trivial questions.

Wednesday, 27 May 2015

Unity's new event system

Despite being very poorly documented, Unity's new event system can be incredibly useful. Here's a really simple script that I keep using over and over.




Saturday, 15 February 2014

Regarding Meshes in Unity

Maybe it's just my OpenGL (1.1) background but here's a few roadblocks I've hit while doing procedural Mesh generation in Unity, along with a few tips not many people seem to know of. Some of this knowledge has been useful even outside my procedural experiments.

Quick Overview (stuff you really should know)

  • You will read this until your eyes bleed
  • Mesh.vertices contains your vertices. Mesh.triangles contains indexes to the vertices array. 
  • Normals (and UVs) are per Vertice. E.g.: Mesh.normals[i] has the normal for Mesh.vertices[i] (Blender uses normals for each face, which sometimes confuses people)
  • Different materials means different submeshes (or a new Mesh if that's what you're into).

A few pitfalls and tips

  • Mesh.uv1 != Mesh.uv (WHY AREN'T MY TEXTURE COORDINATES DOING ANYTHING?)
  • If your mesh has more than  one material, you have to use submeshes to define which area has a certain material. When copying meshes, I've found that I have to manually SetTriangles() as no other way of copying submeshes seems to work.
  • The backface is determined by the order of the vertices in each triangle, NOT its normal. If your mesh looks like it's inside out this is probably why.
  • Some of Unity's built-in shaders (namely the bump mapped ones) do not calculate their own tangents. Each Mesh has their own tangent array for this specific purpose. Unfortunately they can't be auto-calculated.
    • Blender files do not have these by default but fortunately Unity can calculate them automatically. Sadly, we don't have access to their algorithm for this.
    • Fortunately there's some code floating around that works. 
  • Don't generate a new Mesh() every time. Use the same mesh instance and .Clear() it. New meshes will get fed to the GPU but won't replace the old data there, causing memory leaks.
  • 99% of the time you can just call Mesh.RecalculateNormals() at the end instead of reinventing the wheel and calculating your own normals. As far as I know this calculates the normals based on the order of the vertices. 
  • Don't forget to Mesh.RecalculateBounds() if having decent bounds is important to you.
  • When you add a collider Unity will automatically fit it to the current Meshfilter's bounds.

Wednesday, 9 October 2013

Easy Paralax scrolling on a 2.5D game

Classic 2D sidescrollers used a technique called parallax scrolling to make their backgrounds more realistic. Classically it was done by making background sprites move at different speeds, thus creating the illusion that some of them were closer to our eyes. While making Slinki we've done some experiments on this and developed a simple way to replicate this technique that will work in any (most?) 3D engines without too much work.

This article may also be useful if you want to make some part of your game "purely" 2D and have other bits be more realistic 3D meshes.

Sonic 4 paralax
Unfortunately you'll still have a lot of work ahead of you to make backgrounds this gorgeous *sigh*


First we need 2 cameras:
  •     A main camera (the orthogonal one) - This one will render nearly all the game
  •     A second camera, a perspective one - This will render just our backgrounds
Setup your background items, and put them on a special layer (we call ours "Backgrounds". Here's an example, the large panels are all part of this layer and they're ordered according to distance:




Make the second camera follow the main camera. In Unity3D you can simply make it a child GameObject to save yourself a small amount of coding. Also make sure the main camera is drawn first. In Unity this is done by adjusting their depths (0 for the main camera, -1 for the background).

Now the fun part: The main camera should NOT draw the background. This may vary depending on the engine you're using. In Unity you can simply put the backgrounds on a different layer and tell the main camera not to draw it using an occlusion mask. Make sure any empty space rendered by the gameplay camera will fail the depth-test (on Unity this means setting the Clear flag to "Don't Clear").




Make the second camera draw nothing EXCEPT objects in the background layer.


How this works

The first camera will be set to draw all the foreground items and will leave empty space for the second camera to draw on. The second camera will draw the backgrounds in that empty space, using perspective, doing precisely what a parallax scrolling effect tries to replicate.


Here's a couple of animations showing the game in pure orthogonal mode and with our "paralax scrolling".
Entire game in orthogonal projection

Backgrounds using perspective camera


Monday, 9 September 2013

Simple AI in Unity3D

Here's a short writeup on how we're doing the enemy AI for our most recent game, Slinki. I recommend you read up on C# delegates and Unity coroutines if you're not familiar with either.

We decided early on that the enemies should have really simple behaviours. For instance, here's an example of how the Shorg works on the newest version:
  1. Wait until Slinki comes close
  2. Appear and jump out once he's close enough
  3. Wait for 2 seconds
  4. Jump towards slinki a certain small distance
  5. Go to 3
Things like these are really easy to implement using easy AI techniques such as state machines.

The method

Create a new MonoBehaviour for your AI. It should look like this:
//this is like a template for all our states
public delegate IEnumerator State();

//the current state
private State stateFunc; 

//seconds between AI updates
public float AIupdateFrequency = 0.1f; 

void OnEnable() {
 //Sets the first State
 stateFunc = StateWait;
 StartCoroutine (Action());
}

public IEnumerator Action() {
    while (true) {
        //Waits untill stateFunc is done before proceeding
        yield return StartCoroutine(stateFunc());
    
        //Waits for AIupdateFrequency so we don't busy-run our AI logic
        yield return new WaitForSeconds(AIupdateFrequency);
    }
}

Here's an example of a possible state method. This one just makes Shorg stand still for 2 seconds before changing to the "Hop" state.
IEnumerator StateWait() {
    yield return new WaitForSeconds(2);
    
    //next state
    stateFunc = StateHop; 
    yield return null;
}

Here's another state method, this one applies gravity while Shorg is airborne. Once he lands he goes back to waiting.
IEnumerator StateAirborne() {
    kinController.jumpSpeed = -kinController.gravity * AIupdateFrequency;

    if (kinController.isGrounded) {
        stateFunc = StateWait;
    }
    
    yield return null;
}

Guidelines

The "rules" for writting new states are simple: Following the delegate - they should be functions that return IEnumerator , they should end in yield return null,  and they need to have one or more conditions for changing the stateFunc variable (i.e. change to another state).

 

Summary

Advantages of this method:
  • Simple
  • Easy to create new states
  • Very easy to debug just using prints
  • Self destructs cleanly if the GameObject is destroyed or disabled
Disadvantages
  • Can get complicated as the AI gets more complex
  • No way to enforce the guidelines due to the way Unity and C# work
  • Coroutines can get a bit funky to use for an inexperienced programmer
  • State is lost if the gameObject is temporarily disabled

Special thanks to David Craft for this amazing hack that allows code syntax highlighting on blogger


Note: If you need to temporarily run the AI logic more often than AIupdateFrequency will allow, all you need to do is yield inside a cycle. This probably sounds confusing so here's another version of the Wait state. In this one Shorg turns towards the player before waiting:

IEnumerator StateWait() {
 
    //Facing wrong way?
    while (Vector3.Dot(transform.forward, slinkiDirection.x * Vector3.right) < 0) {
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(dir), Time.deltaTime * 100);
        Debug.Log("Turning around");
        yield return null;
    }
 
    //Debug.Log("Waiting for 1 second");
    yield return new WaitForSeconds(1);
    stateFunc = StateHop;
}

That while cycle will make the coroutine run every frame update. Without it, Shorg would only try to face the player once every 0.1 seconds, producing a very jerky animation.

Saturday, 6 April 2013

Unity3D Version control with Dropbox and Mercurial



After a few months I think we're ready to share our Unity3D (free) version control setup. Keep in mind this is not ideal and it was designed to hack some sort of code tracking into the free version of Unity. We are using mercurial but there isn't (shouldn't be) any reason it wouldn't work with any other type of version control system. Always be aware you shouldn't have more than one person editing the files that are not on your VCS.

I'll assume everyone reading this has a basic knowledge on Mercurial and Aliasing/Symlinking and go straight to the point. If you need anything more specific feel free to comment and I'll consider adding it.


The concept:

There's 2 types of files in our project: binaries which we don't/can't synchronize (Unity Pro and the asset server solves this somewhat) and code (text) files. We don't want to do version control for binary files. Let's begin by putting all our binary files into a separate folder. This is what our project's hierarchy looks like:


 

Setup:

First thing's first, launch your project and go to Edit->Project Settings-> Editor. In the inspector change the version control mode to meta files and Asset Serialization to Mixed mode. This means from now on all the data on your Prefabs, materials, scripts, etc will be store in .meta files in their respective folder instead of clumped up in the Library folder.




Basically we just shove everything that's not a text file into the Binaries folder. Close unity, take this folder and put it's contents into a Dropbox folder (we'll be using "\Titan Forged Games\Brian Storm\Unity Project\Assets\Binaries").

Create the repository. This is the contents our .hgignore file (aka the files and folders our repository should ignore):

syntax: glob
     Library/
     Temp/
     Assets/Binaries

     *.userprefs 
     *.pidb
     *.unityproj
     *.csproj
     *.asset
     *.cache

    Assembly-CSharp-vs.csproj 

    Assembly-CSharp.csproj
    ourProjectNameGoesHere.userprefs

    *.orig

    *.orig.meta



The Library folder should never be synced. Doing so is a recipe for disaster. It has local data regarding the project and will always be regenerated based on the .meta files. The library folder will ALWAYS be unique for every person so DON'T even try to sync it and always make sure it's not being shared (we almost lost an entire project due to a silly mistake with the Library folder being corrupted on a single machine).

The rest of the list exists mostly to keep useless binary data or personal preferences from our repository. The .orig are files generated by mercurial if you wish to store backups of files before a merge operation - feel free to ignore that line (it's just personal preference).

 

How to use it:

Clone the repository.
Create a symlink (or shortcut) for the binary files in the Dropbox folder.

In our most current project we're using the dropbox folder "Titan Forged Games\Brian Storm\Unity Project\Assets\Binaries" to "place" binaries into our repo's "Assets\Binaries"

On windows 7 (and 8) you can launch the command console and type: mklink /J "YOUR REPO PATH\Assets\Binaries" "C:\Users\YOUR NAME\Dropbox\Titan Forged Games\Brian Storm\Unity Project\Assets\Binaries"

From now on, everything that is on "C:\Users\YOUR NAME\Dropbox\Titan Forged Games\Brian Storm\Unity Project\Assets\Binaries" will be identical to
"YOUR REPO PATH\Assets\Binaries"


Notes:

  • Don't ignore the newly created .meta files when commiting a new code file. They are what allows Unity to know if your GameObjects use a certain script (otherwise you'll just get missing script Errors on GameObjects that use them).
  • When testing things out and doing drastic changes it's best to avoid people tweaking an editor scene (besides not being able to work on the same scene at the same time, it's also likely he's messing with inspector attributes that will no longer exist once you commit your code).
  • The silly mistake I mentioned earlier deleted all our binaries on the dropbox folder. Don't be silly and do regular backups of the Binaries - in fact, just backup your entire project once in a while, you'll be thankful for it some day.