Tag Archive | unity3d

Unity3D: where do we go from here

Finally doing something useful instead of promoting my game. Today is the day the foundation for a new project has been laid, and it started with pathfinding for my future virtual minions.

A* (pronounced “A star”) is a best-first pathfinding algorithm which produces least-cost optimal path from point A to point B, you can read everything about it on Wikipedia, but you don’t have to implement it yourself, not because I’m sharing my Unity3D C# static class with you, but because there’re probably a hundred of different implementations already.

Made a small vid showing how it works:

 
(Notice capsule moving diagonally in open unobstructed spaces – that’s a result of pretty simple path smoothing addition I made to classic A* implementation.)

I already used A* pathfinding algorithm in Railyard for building routes, but back then it didn’t account for obstacles and there was no path cost estimation. Now I finally made it something complete. My implementation uses spherecasting to check for obstacles in a way characters won’t hit corners when traversing the path. (Make sure your obstacles are on “Obstacle” layer and they all have non-trigger Collider on them.)

Now, open that gist, copypaste into your project and use AStar.FindPath() method, supplied with two Vector3’s to find best path between them. You want smooth, non-“pixelated” path like in the video? Use AStar.SmoothPath() with a path from first method to get it smooth. You’ll probably need to adjust some values to be in the scale of your game (I use 1.0f scale everywhere, mind that), so read comments in the class, there’s enough info for you to understand what’s under the hood.

Go now, you can thank me later.

Advertisements

Unity3D: colliders are your friends

BjhqFlsCYAArgFY

Here’s another portion of Unity3D beginner tips and tricks, and today it’s about using physics engine for something more than just making things go bump. (Pic related.)

Tip #1

Did you know, that every collider you click/tap sends an event to all the scripts attached to the same gameObject? Now you do. Implement void OnMouseDown() method in any of those scripts to get the message. Make sure your object is not in Ignore Raycast layer though, ’cause raycasting is what making these messages possible. A pretty useful mechanic for implementing UIs (since you can attach colliders to virtually anything) or otherwise interacting with objects in the scene.

Tip #2

Next one is more complex. Let’s say you got objects that need logical connection to each other. See Railyard, trains are being made of cars of the same type. First solution that comes into mind is just store references to cars in arrays and do a bunch of array processing each frame. (That actually works, and I did implement that in the early prototype.) But making your hardware do extra work is unnecessary, especially when you have access to a perfectly optimized physics computation.

So, what I did was this:

colliders

Except main collider used for actual collisions and destruction, every car has two sets of colliders – box and sphere, with sphere colliders being triggers. Note: triggers ensure non-trigger colliders will go through them, and redundancy of colliders on each side ensure void OnTriggerEnter() will run on every car no matter which one initiated a collision.

Rest is also simple – on every trigger enter event a link between two cars is created if it doesn’t exist yet, link being a simple struct with two references to cars. Link is placed to a simplest collection possible (I used C# List). On every trigger exit event existence of a link between two cars is checked and link is destroyed if exists.

I find this realization simple and efficient when it comes to something like match-3 games, so if you’re doing one, hope it helps.

Unity3D: killing them softly

I promised to write, and there’s not much to write about lately, and I’m kinda busy and determined to finally finish Railyard this week, but promise is a promise – new portion of Unity3D tips and tricks for beginners comin’ right up.

Trick #1

You need some nice visuals to kill an object in the scene, be it blown up, burnt or just shot in the head. Most basic “death” effect that leaves no traces of the previously existing object is dissolution – as seen in Doom 3 or Unreal 3 (or Bureau XCOM, not sure about that one) after shooting some bullets in some alien’s head, or in this picture of Hogwarts’ shield failing:

NewHogwartsDH

This effect can be achieved with built-in alpha cutoff shader. First, you’ll need a separate “death” material with a shader from “Transparent/Cutout” group, that you’ll apply to your renderer when kill sequence is initiated. Second, you’ll need a separate texture for your object with an alpha that looks like this (note, making those clouds less blurry will not look good on small objects while dissolving):

clouds

Third, you’ll need to animate the cutoff value on your material from 0 to 1.0f in your code:

renderer.material.SetFloat("_Cutoff", timeElapsed);

That’s it, you’re done dissolving your enemies. Oh, you wanted glowing edges too? That’s not beginners’ stuff, and requires a custom shader, you can read about it in this forum post.

Trick #2

This really comes in handy when you got a particle effect attached to the object you destroying. Particles got their own lifetime and just removing them from a scene in an instant is not cool. So what should you do?

First, make sure your particle systems are on separate GameObjects within hierarchy. This will let you detach them on parent’s destruction – like this (this should be called from script attached to root GameObject):

void OnDestroy() {
    transform.DetachChildren();
}

Now all the particle systems are detached from their parent, but maintain their position/rotation/scale. Two moments here: 1) if your particle systems are looped, you should stop them now and 2) if you stopped them before detaching and they have “play on awake” ticked, they will start emitting again after detaching.

Second part – how to avoid cluttering. When stopped, PSs still consume memory, so you have to kill them somehow after they completely done. A simple script I wrote will help:

using UnityEngine;
using System.Collections;

public class SelfDestruct : MonoBehaviour {

    private bool sequenceInitiated = false;

    void Update() {
        if (transform.parent == null && !sequenceInitiated) {
            sequenceInitiated = true;
            float destructIn = 3;
            if (particleSystem != null) {
                destructIn = particleSystem.duration;
                particleSystem.Stop();
            }
            StartCoroutine(SelfDestructionIn(destructIn));
        }
    }

    IEnumerator SelfDestructionIn(float seconds) {
        yield return new WaitForSeconds(seconds);
        Destroy(transform.gameObject);
    }
}

When detached from a parent (means parent == null) the script will initiate a self-destruction sequence, which length is determined by particle system if current gameObject has one, and also stops the emitter. Just attach this script to a gameObject with a particle system inside your actor’s hierarchy.

More tricks to follow, requests accepted.

Panic!

Not much to tell about, except in the last week I’ve build a party game with Unity3D using only NGUI. Coming soon to iOS, Android and probably WP8, if I can figure out Microsoft’s publishing process.

Unity3D: loading external images

So I’ve been doing various tests to see if I can port Harmoniq, a project of mine, to Unity3D for crossplatform reasons. And not only crossplatform, and this is what this post is about.

You see, any heavy image processing operation written in native iOS code consumes shitload of memory and processor time. In fact, so much that I’ve been optimizing them for 3 months and still get user reports about performance and memory problems. Imagine, I had to write about 200 lines of iOS native code to get single pixel from a photo and not crash the app due to memory pressure. Now, imagine a color picker that can be dragged across the photo taking pixel samples – realtime. Unity does this with single GetPixel() call.

So, Unity pixel sampling performance is perfect, as expected, it’s gaming engine after all, it’s supposed to work with textures reeeeeallly fast. What’s unexpected is how Unity loads textures from external resources, be it web or device storage. The most common scenario is this: (code ahead)

Read More…

Unity3D 5 Feature Preview

 

Unity3D 5 has been announced today at GDC. Watch feature vid for instant nerdgazm.

Unity3D: save game basics

So, you finally built a game on Unity3D that has more than one scene. Congrats. Now you got bunch of user and game generated information you need to pass from one level to another or restore on scene reload. The simplest way to achieve that is XML object serialization/deserialization and saving/loading XML files. Today we gonna do just that.

Brace yourselves, code is coming.

Read More…