• Home  / 
  • Author's archive:
About the author

Jason Weimann

VR Movement – Ironman / Jetpack Flying with SteamVR

There are a lot of interesting movement systems for VR.  Arm swinging, dashing, teleportation, trackpad, and more.  In this guide, I’ll show you another one I experimented with previously and really enjoyed.  We’ll go over how to make a player fly like Ironman or at least like a person holding some jet packs..

Prerequisites

This article assumes you have SteamVR in your project, though converting it to OVR native should be a simple task.

Rigidbody on [CameraRig]

Start by adding the [CameraRig] prefab from the SteamVR package to your scene.

Add a Rigidbody component to the camerarig.

Freeze the rotation values.

Locking rotation is very important, if you don’t, your player will end up spinning around, flipping over, and getting sick

Now, add a box collider to the rig so you can land (this could be a capsule or any other collider that works well for your game)

Controller Setup

Expand the CameraRig and select both controllers.

Add the SteamVR_TrackedController component to them both.

JetpackBasic Script

Create a new script, name it “JetpackBasic”

Replace the contents with this.

Your controller should look similar to this: (the sphere collider and audio source are optional and beyond the scope of this article)

Press Play

Aim the controllers where you want to go.

Pull the trigger.

Fly!

Continue reading >
Share

How To: Fix bad -90 x rotation in Unity3D with Blender

Every Unity developer will eventually come across art assets that aren’t rotated right for Unity.  Most of the time, it doesn’t matter and you can simply rotate the objects in your scene.  If they’re static or not rotating from code, there’s really nothing to worry about.  But when your character model’s forward is pointing out of their head, something needs to be done to fix the rotation.  There are a couple ways you can fix the -90 x rotation issue.  One quick & dirty method is to parent the model to another game object and only ever rotate the parent, this works great for most cases.  Today though, we’ll cover how to fix this rotation on the actual model in blender and re-export it with the forward direction facing where it should.

Blender

If you haven’t used blender, don’t worry, I’ll walk you through the parts you need step by step.  If you don’t have blender installed, you can download it free here: https://www.blender.org/download/

The Example

Take a look at this character body.  It looks right, but the rotation is -90 on the x.

If we reset the rotation you can see that the forward vector is actually pointing up out where the head goes..

Let’s fix it

It’s time to open blender and get this model fixed up.

Once you launch blender, select File->Import->FBX

Browse to your model and select Import (or double click it)

To the right, you should see your blender scene view.  It’s similar to the Unity Scene hierarchy and shows you the objects in your scene as a tree.

Because we imported this FBX into a ‘new project’, there’s a bit of extra stuff.

You can right click on the extra stuff to delete it all.

In my case, I’m deleting the “Camera“, “Cube“, and “Lamp

After I’m done, it looks like this

 

Okay, it’s time to rotate!

Now that we have the model imported and the scene cleaned up, let’s fix the rotation.

Select your model by right clicking on it OR left clicking it in the scene tree view.

On the top left, under Tools, you should see a “Rotate” button.

Click Rotate.

If you look down, you’ll see that a rotate dialog is now visible.

Set the Angle to -90  (make sure it’s negative).

Check the “X” box for Constraint Axis (we only want to rotate this on the X axis)

Applying the Rotation

Move the mouse over the model

Using the keyboard, hit ctrl-a.

You should see a dialog like this.

Click Rotation

Exporting the Fixed Model

Rotation is done, it’s time to export our fixed model.

In the menu, select File->Export->FBX

Give the model a new name (or overwrite your existing if you have it in source control)

Click Export FBX

Now jump back to Unity and check out the fixed rotation!

Continue reading >
Share

Rename Serialized Fields

By Jason Weimann / July 7, 2017

I talk a lot about the [SerializeField] attribute. It’s one of the things I like to beat into new Unity developers to keep them encapsulating their code. Being able to assign values or references to fields in the Unity editor is one of the great things about the engine. But if you’re refactoring often enough, you’re bound to come across a situation where you need to re-name a field. If you just jump in and re-name the field though, you’re gonna break things.

Why will renaming break stuff?

Let’s take a look at a scene that I’ve saved (I set serialization mode to “Force Text” so we can read it)

I have a simple scene with an object that contains two serialized fields.

One’s a float, the other is a reference to the camera in the scene.

Here’s the code for that example script.

Let’s see what that ExampleScript data looks like when it’s serialized into the scene file.

The last two fields show the data for this example script.

We have a floatValue set to 5 and a cameraReference for the camera.
Now, if I rename the fields like this.

When the editor tries to find the values for these new fields, they won’t match and we get this.

Because our fields are serialized with different names, there’s no way for the editor to know we want it to preserve those values.

FormerlySerializedAs

UNLESS we use the attribute [FormerlySerializedAs].

This attribute tells the editor that we want it to look for the current name first, but if that’s not found, look for the former name.
If the new name isn’t found, but the former one is, the editor will pull in the old value then re-serialize it with the new name.

Removing the attribute?

Once you’ve re-named your field, and re-saved every object using that (scenes, prefabs, scriptedObjects), you can remove the attribute. Unless it really bothers you though, I haven’t seen any actual reason it needs to be done. If you decide to do it though, just make sure you’ve committed everything to sourcecontrol first so you don’t lose anything.

Continue reading >
Share

Pixel & Vertex Lights in Unity3D

By Jason Weimann / July 6, 2017

If you’ve heard the terms “Pixel Lights” and “Vertex Lights” but weren’t quite sure what they meant, this article should help you get a basic understanding of the differences.

When working in Unity, you can choose between Forward or Deferred rendering.  I won’t go deep into the differences of these two today, but may cover them in the future.

For this article, we’ll be working with Forward rendering.  Most of my recent game development has been in VR, and forward rendering tends to be a great choice for VR games that need every ounce of performance they can get.

What’s the visual difference between Pixel & Vertex lighting?

Pixel Lights determine shading for each pixel of the object being shown.  Vertex lights will calculate the lighting of each vertex and interpolate between them.

Sometimes vertex lighting is ‘good enough’ (more often when objects are further away).  Sometimes it looks terrible and needs to be addressed.

To show the difference between per pixel & per vertex, here’s a visual example.

Pixel Light

You can see our spotlight renders as you’d expect.  Light is shone on the sphere and the ground below it.

Vertex Light

With the vertex light, we see a totally different story.

How did I toggle this? – Render Mode

For the demo pictures above, I changed the “Render Mode” of the spotlight to “Not Important”

How many will be pixel lights?

You can force your lights to be pixel lights by setting them to “Important”.  You generally don’t want to do this for all of your lights, but if you have a very ‘important’ light, you can force it to be a pixel light.

By default, the lights are set to Auto.  In Auto mode, the lights are prioritized by intensity and distance from the object.  Closer / brighter lights are rendered per pixel and the others are vertex lights.

The number of lights that will be set to a Pixel light is determined by your quality settings.

You can see the setting under the “Rendering” section.  Here’s the default for “Good”.

Quality Level Pixel Lights
Fastest 0
Fast 0
Simple 1
Good 2
Beautiful 3
Fantastic 4

Changing Quality Settings

To wrap this up, I wanted to show how this can matter when you change quality settings.

Here’s a cube with two spotlights on it set to Auto.

When I change the quality settings to Simple though, take a look at the change.

Remember “Simple” defaults to 1 pixel light.

Continue reading >
Share

A simple Unity3D UGUI Popup Dialog/Window with no code

By Jason Weimann / July 3, 2017

This guide is intended for people who have little to no experience with UGUI and want to have a popup or toggled window in their Unity3D project.  We’ll cover how to setup that window, create the buttons for toggling it, and hook everything up without writing any code.  There is also a sample project at the end you’ll be able to download and use as an example for building your own popup dialog.

Project Setup

First we need a new scene with a new canvas.

Under the canvas, create a new gameobject.

Name it “Popup Window”

Set the transform values to this

Create a Panel under the Popup Window.

Name it “Toggled Panel”

Inspector Values

The button

Create a button

Name it “Show Button”

Make it square by setting the Width and Height to 30.

Under the button, create a text object and replace the text with a “+

It should start to look a bit like this.

It’s time to add events.

Select the “Show Button”

Under the Button component, add an OnClick event by clicking the “+”

Drag the toggled panel into the event.

Using the dropdown to the right, select GameObject->SetActive

Check the box (this means set the toggled panel to active).

Click the “+” again to add another handler.

This time, drag the “Show Button” gameobject onto it (make sure to drag from the scene view).

Select GameObject->SetActive, and leave the checkbox unchecked.

The Minimize Button

So far, we can open up the panel with our button.  If you disable the panel and hit play, you’ll see the panel appears and the button is disabled.

Now let’s add a way to minimize / hide the panel and re-show the expand button.

Select the Show button

Duplicate it

Move the Duplicate to be a child of Toggled Panel

Rename it “Hide Button”

Change the Text child’s “text” value to be “-“

The Hide Events

Our Hide button has some events already hooked up to it because it’s a duplicate of the show button.

Let’s modify those events to do what the hide button should do..

Select the “Hide Button

For the first event, uncheck the box.  This will make “Toggled Panel” inactive when we click the Hide button.

For the second event, drag the “Show Button” into the gameobject area.

Now, the Hide button will turn on the show button, and turn the popup off (which the hide button is a child of).

That’s it, everything should work now.

Press play and try out your toggled window.

Try adding some extra stuff to the popup window..

Consider finding new images to use in place of the Text objects, there are 100’s you can find with a quick google search like this:

https://www.google.com/search?q=expand+button&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjMxPvTgu7UAhUY-2MKHSQyCmIQ_AUIBigB&biw=2560&bih=1421#q=expand+button&tbm=isch&tbs=ic:trans

 

Project Download

You can download the full example project here: https://unity3dcollegedownloads.blob.core.windows.net/vrgames/UI%20Popup%20Menu.zip

Continue reading >
Share

Using Vector3.Reflect to cheat ball bouncing physics in Unity3D

Games based on balls can be a frustrating to build.  I’ve done a number of them myself and used a variety of different techniques.  The hardest part tends to be getting the physics right.  Some games require a ton of tweaking, adjusting rigidbodies, colliders, physics materials and scripts.  But in some other games, cheating is the way to go..  Cheating by not using the physics system for bouncing..

Cheating How?

Instead of allowing the physics system to control our ball bounces, we’ll create a simple script to do it instead.  Instead of adjusting the mass, bounciness, & friction our script will have a single float for the minimum bounce velocity.  This will keep our ball bouncing forever, and always at about the same speed.

What’s it look like?

The Code

Review

There are a couple things to cover here, we’ll go over them in order.

To start we have a Vector3 for an initial velocity.  Like the tooltip says, this is just for the example / debugging.  Our OnEnable method will set the initial velocity to this value so the ball starts moving.

The minVelocity field is used to control how slow the ball can go.  Every bounce will be at this velocity (or higher).

OnEnable() – Here, we’re caching the rigidbody reference and setting that initial velocity.

Update() – This one’s important.  Because we’re going to override the collision behavior, we need to keep track of the objects velocity each frame.  When the collisions happen, this velocity is going to change, but for our calculations, we want the velocity before the collision.  Saving it off here in Update is an easy solution.

OnCollisionEnter() / Bounce() – This is where we do the work.. even though it’s not much work.  Calculating direction is done using Vector3.Reflect.  We pass in the last frame velocity (that we cached in Update), along with the collision’s normal.  Then we multiply the result by the current velocity OR the minVelocity, whichever is greater.

Bouncing toward the player

In games where you have the player hitting a ball against a surface, you’ll often want to send the ball back toward the player.  This might seem ‘not realistic’, but it’s usually way more fun.  And it’s pretty easy to do.

The Code

The only real difference is when you’re setting the return velocity, we’ll lerp between the direction to the player and the reflect value.

In the editor, we expose a bias field that allows easy tuning of just how ‘toward the player’ the ball goes.  The right value for the bias will depend on your game and the play area size.

Example Download

If you want to try this out and don’t want to setup a couple cubes, you can download the example project here: https://unity3dcollege.blob.core.windows.net/site/Downloads/Ball%20Bounce.zip

Conclusions

This functionality isn’t appropriate for every game, or every interaction in every game.. but there are plenty where it works better than using the default physics setup.  Especially the bouncing towards a player.. I’ve used that more than once and found it always made the games more fun and engaging.  It’s also worth noting that you can use Vector3.Reflect for all kinds of other functionality, reflecting bullets, beams, or anything else.. so keep it in mind when coming up with new game mechanics 🙂

Continue reading >
Share

Sliding a UGUI Mask

By Jason Weimann / July 2, 2017

The UI Mask component in Unity’s UGUI system is pretty powerful.  If you’re doing any UI work haven’t used the UGUI mask before, make sure to check out the primer video here when you’re done reading this article 🙂

In this article, I’ll show you how to use the UI Mask component for a very specific case, to slide an image over another image..  or to ‘replace an image with another’.

To control the sliding, we’ll use a basic UGUI slider, though you could easily modify the solution to fit any other input source.

UGUI Mask Slider – Setup

To start, create a canvas.

Under the canvas, add a slider & a panel.

Set the panel transform values to match this.

Under the panel, create an image.

Rename the image “Starting Image”

Adjust the rect transform to stretch and fill (hold ctrl/cmd & alt)

Replace the “Source Image” with this image (save it into your project and change the image type to sprite first)

The Mask

It’s time to create our mask image.  To do this create a new image under the panel.

Name it “Mask”

In the Inspector, add a Mask component.

Uncheck the “Show Mask Graphic” box.

The overlayed Image

Under the mask, create the image for the overlay.  Name it “Overlayed Image”

Set the “Source Image” to this image and set the rect transform to stretch.

Script Time – Almost Done!

Create a new script named RectTransformLockPosition and replace the contents with this:

Add the RectTransformLockPosition component to the Overlayed Image.

Moving the Mask

Now we need something to move our mask..  we’ve created a slider, but we’ll need a little code too.  (in your project you may move this completely different, this is just an example of one way you can move the mask)

Create another script named SlidableMask and replace the contents with this:

Attach the SlideableMask component to the “Mask” gameobject.

Drag the slider in the hierarchy onto the Slider field to assign it.  This will link the slider up to the mask.  (the code will register the listener for you)

Save and Press Play!

Conclusions & Alternative Methods

You may be wondering if this is the best way to accomplish this effect.  Depending on your situation, it may not be, you could get a similar effect from a custom shader or some other cool tricks.  But if you’re comfortable with UGUI, it’s an easy and extensible way to replace or reveal an image (or other stuff, no reason you couldn’t have an entire panel of other components back there).

Special Credit

I stumbled across the idea of RectTransformLockPosition on stack overflow or unity answers, but I can’t find the original source.  But I still wanted to note it and give credit, so I’m gonna keep searching for that source to share 🙂

Source

Want the project source?  You can download it here: https://unity3dcollegedownloads.blob.core.windows.net/vrgames/Masked%20Slider%20Image.zip

Continue reading >
Share

LINQ for Unity Developers

LINQ (Language Integrated Query) is a great feature available to C# Unity developers.  Many developers don’t know it exists or how to use it though, and lose out on the great time & code savings it can provide.  LINQ in Unity has a variety of great uses, and a couple pitfalls you’ll want to avoid.

Getting Started

To use LINQ in a C# script, you need to add a using statement for the namespace like this.

What Can I do with LINQ?

The most common uses for LINQ statements tend to be sorting, searching, and filtering (though there’s plenty more you can do).

For example, let’s take a scenario where we want to find the closest game object to the player.

Compare that to the LINQ version

As you can see, LINQ has an OrderBy extension method for collections.  Because we have a List of gameobjects, and List implements IEnumerable, we can use OrderBy to easily sort objects by distance, then take the first from the collection (since they’re in ascending order).

What the hell is that t => ????

You’ll see this a lot in LINQ statements, it’s called a lambda operator.

In the case of this OrderBy statement, think of the “t” as a reference to each object in the collection.  When it orders them by distance, it’s passing in our local objects position, and the position of “t”.

Does it have to be “t”?

That “t” is just a variable name.  It could just as easily be named “a”, “thingToCompare”, or any other variable name.  “t” is just a common standard in lambda examples.  Often, I’ll use a variable name that’s more descriptive, especially when building more complex LINQ statements.

What’s FirstOrDefault?

The FirstOrDefault() call makes our LINQ statement return the first object from the collection… OR whatever the objects default value is.  Default is just the value you’d have if you never assigned a value.. for objects that’s null.

There’s also a First() method, but that will throw an exception if there’s nothing in the collection.  Sometimes you want this, but I find myself almost never using it.

What about Performance?

Of course with anything, you’ll need to consider the performance of operations like this.  In the majority of cases using LINQ won’t hurt you at all.  It may add a couple nanoseconds here or there, but it can also shave some time off if your custom code isn’t completely optimized.

The one thing you definitely do need to look out for though is Garbage Collection.  LINQ statements will generate a little garbage, so avoid using them in something that’s going to be called every frame (don’t put them in your Update() calls).

For other events though, LINQ can be a huge time saver, make your code easier to read, and having less code always reduces the chance for bugs.

Multiple Lines or One Line?

When you look at LINQ statements, sometimes they’re written as a single long line.  Sometimes there’s a line per method..

Functionally, it doesn’t make any difference.  Personally, I prefer a line per method because it makes the call easier to read at a quick glance.  So while there’s no set rule on it, I recommend you split your LINQ statements with a new line before each method call (with the period on the newline).

Take()

The Take method can be used to “Take” a subset of a collection and put them into another collection.

As an example, imagine a case where you want to find the 4 lowest health enemies.  The Take method makes that easy.

Sorting by multiple things

You saw the OrderBy() method above, which is great for sorting, but sometimes you’ll need to sort by more than one thing..  For example imagine you have a scene full of Dogs… and you want to sort the dogs by Color and Size.

Switching The Order

If you want to sort in the opposite direction, you can use OrderByDescending() to reverse the order.

Deferred Execution

Often when you see a LINQ statement acting on a collection, you’ll see it end with ToList();

There’s a very important reason this is done.. and that reason is called deffered execution.

When you use a LINQ statement, the execution of the statement doesn’t happen until it’s needed.

Take a look at this example:

The ordering and distance checking of coins is only done if the player presses ‘A’.  And even then, it’s not until the delay has passed and we’ve reached the foreach statement.  If that’s never reached, the deferred call isn’t needed so it’s never run.

The downside to this is we have a bit less control over execution time.  Sometimes that’s fine, other times we want to enforce execution immediately.

And to force that execution, we can call ToList() or ToArray().

What about the other syntax?

It’s important to note that there are two different types of LINQ syntax.  There’s the one I’ve shown you so far, and another that looks a bit more like SQL.  For Unity developers, I’d recommend staying with the fluent syntax you see here and avoid the SQL one.  I’ve found developers who don’t do much SQL work tend to get a bit more confused by the other syntax and confusion causes bugs.

What other operators are there?

There are a TON of them.  I’ve covered a couple of the most common ones, but I recommend you view the larger list here just to know what’s available:
https://www.tutorialspoint.com/linq/linq_query_operators.htm

Here are some of the ones I find myself using more often

  • GroupBy() – groups things as you’d expect.. often end up using this with ToDictionary
  • ToDictionary() – yep it builds a dictionary with the keys/values you want from any other collection(s).
  • Any() – tell you if any object in the collection meets a criteria (returns true or false)
  • Skip() – great for paging, often used with Take
  • Contains() – easy way to check if a collection contains a specific object

Conclusions

LINQ is amazingly powerful, and with just a little time learning the syntax, it can be a huge time saver.  It’s also important to be able to read in other people code..  Outside gaming, in other C# projects, you’ll see LINQ everywhere.  As I mentioned above though, garbage collection and performance are extremely important for games, so you still need to think and profile when using it in your projects.  That’s true for everything though, so don’t let it discourage you from taking advantage of this amazing language feature.

For more examples and LINQ statements, check out this site: http://linqsamples.com/

Continue reading >
Share

How to looking inside or through a wall on HoloLens

If you’re developing for the hololens, one of the coolest features you can have is see through walls.  Of course you can’t really see ‘through’ a wall, but you can place holograms in a way that they look like they’re inside or behind the wall.  For this to work though, you need to be able to mask out the wall in the foreground.

As an example, I’ll show a breakable wall we built at the last HoloHack, where you could see the cheese inside.

The wall is made up of 4 parts..

  1. Plaster
  2. Bricks
  3. Cheese (inside)
  4. The Occluder (makes it all work)

 

Plaster

Bricks behind the Plaster

Cheese behind the wall

 

It’s hard to see in screenshots, but the 3d depth really shows when you look on the hololens.

What’s with the big black cutout?

That’s the occluder.  It’s actually just a mesh, cut out int he shape we wanted the wall.  The material on it is using the Unlit Color shader set to black.

On HoloLens, solid black is rendered transparent.  With a mesh behind it, and the occluder on the wall, this actually makes the real world wall not visible, allowing you the ability to see ‘inside’ the wall.

I wish I could show a video of how this works, but recording on a hololens doesn’t show the occluder right (it looks correct in the headset but not the recording).

It’s also very important that you use an unlit shader (either unlit/color, or your own).  Any variance from a true black (0, 0, 0), will prevent this from working.

Important Note: A quad or UI sprite will NOT work.  The object needs a mesh of some sort.  It does work fine with a primitive cube though.

One of the best examples of this functionality I’ve seen is in Robo Raid.  You can see a quick video of it here.

Continue reading >
Share

Unity3D cannon / projectile ballistics

By Jason Weimann / June 30, 2017

One of the first things I created in Unity was a mobile game using cannons.  Figuring out how to launch cannonballs when I was brand new to Unity took me about a day.  But it was a fun rewarding experience, and thinking back on that experience made me want to share the process.  In this post, I’ll show how to use some commonly shared ballistics methods in a sample cannonball launching scene.

Credit

Before going too far, I want to give credit to a post that helped me when I was starting out.  This answer helped me learn and understand ballistics calculations and is the basis for this example.  http://answers.unity3d.com/comments/236712/view.html

Scene Setup

For this example, we need three things.

  • Plane
  • Cannon
  • Cannonball

Create a Plane, reset the transform values to default.

The Cannon

Create a cube.

Name it “Cannon”

Set the transform values to match these.

Disable the Box Collider

Create a material named “Cannon”, tint it grey, and assign it to the Cannon object in the scene.

The Ball

Create a sphere.

Name it “CannonBall”

Add a RigidBody component

Create a material named “CannonBall”, make it solid black, and assign it to the CannonBall object in the scene.

Copy the Transform values below onto the sphere.

The Script

Now that we have the objects setup, let’s take a look at the script.

Code Review

We start the script off with 2 private (but serialized) fields.

The first is a reference to our cannonball’s rigidbody.  To keep this simple, we’re just going to re-use the single cannonball, though in your project, you may want to reference a prefab and instantiate a new one every time the player fires instead..

Next, we have an angle variable.  Being able to adjust the angle of our cannon seems pretty important, so we have it setup as a slider you can play with in the editor.

The Update method waits for your player to click the left mouse button, then it performs a raycast, looking for the point on the plane that they’ve clicked.

If it finds a point, we call FireCannonAtPoint and send it the destination for our cannonball.

From here, we calculate the required velocity by passing our destination and angle into the BallisticVelocity() method.

We then reset the cannonball’s position to the cannon’s center (this should really be another transform at the tip of a real cannon).

And finally, we set the velocity of the cannonball’s rigidbody to the calculated velocity.

Conclusions

Shooting cannonballs, grenades, or other ‘lobbed’ projectiles is a pretty common task in games.  And as you can see above, it’s pretty easy to get working once you have a method for calculating the correct velocity.  This example even allows you to customize the angle, which makes it superior to most of the ones you’ll find in a quick search.  And again, I want to give real credit to the original answer, which I used my first time solving this problem… without people like him answering questions, I’d have blown plenty of time figuring out a workable solution 🙂

Continue reading >
Share
1 11 12 13 14 15 21
Page 13 of 21