World of ZeroOpenSCAD is a tool that can compile programs into 3D models allowing you to code your own CAD designs instead of building them inside of a WYSIWYG type editor like Fusion 360, SketchUp etc.
The module we created for a basic dice looks like this:
Building a Custom Dice Model with OpenSCADWorld of Zero2022-11-25 | OpenSCAD is a tool that can compile programs into 3D models allowing you to code your own CAD designs instead of building them inside of a WYSIWYG type editor like Fusion 360, SketchUp etc.
The module we created for a basic dice looks like this:
Join the World of Zero Discord Server: discord.gg/hU5Kq2uBuilding a Custom Unity Pixelated Post Processing Effect in Shader GraphWorld of Zero2024-06-06 | Lets dive into Shader Graph and how you can use it in Universal Rendering Pipeline Unity projects to create post processing effects for your game. We'll be exploring that by creating a custom pixelation effect that turns any scene we want to render into a pixelated copy of that screen. This allows us to use 3D meshes, high resolution textures and text normally in our scene and still preserve a uniform pixel ratio among all of our assets and even allows us to utilize animations and 3D movement without breaking the effect.
***
Join the World of Zero Discord Server: discord.gg/hU5Kq2uGo Go Godot: New ProjectWorld of Zero2023-06-14 | I've never used Godot, let's explore it together and see what we can build!Trie, Trie Again - A String Search Data StructureWorld of Zero2023-04-10 | Trie's are a sort of prefix search tree that uses prefix substrings to efficiently search and complete a word search. This allows you to search for a string matching a prefix of a large number of strings without having to individually test against every string.
Join the World of Zero Discord Server: discord.gg/hU5Kq2uAn Intro to Json Serialization and Deserialization in UnityWorld of Zero2023-04-09 | JSON is a common data format that stores data in human-readable strings that can be interpreted by computers. This makes it possible for you and other people to read and modify the raw data and pass that information along to internal systems for use. JSON is commonly used across the web and other places and has native support built in to Unity using JSON.NET. In this video we're going to walk through an introduction into how to serialize and deserialize JSON objects in Unity so you can quickly store configurable information about your games in a standard open format.
* `JsonConvert.SerializeObject()`: Serializing object's converts a C# object's data into a string so you can store and pass that information along to other systems. Passing in a class will return a string of the data serialized into a JSON format. You can read that data back out using `DeserializeObject`. * `JsonConvert.DeserializeObject()`: Deserializing object's requires two parameters. The class you want to deserialize the data into and the JSON formatted string you want to deserialize. This method will automatically attempt to convert the provided string into a new instance of the target class and return that class back to you to use. After you've modified data you can write the information back to a JSON string with `SerializeObject`.
When working with strings that span multiple lines there are two Attributes you can add.
* [`MultilineAttribute`](docs.unity3d.com/ScriptReference/MultilineAttribute.html): Multiline strings expand the normal textbox a fixed number of vertical lines. This is less flexible than a `TextArea` but can still be useful in some situations. * [`TextArea`](docs.unity3d.com/ScriptReference/TextAreaAttribute.html): Text Area's span between a minimum and maximum number of lines and - unlike a `Multiline` attribute - they will add scrollbars if the text exceeds the maximum number of lines. Additionally the `TextArea` spans the entire width of the Inspector giving more room to type.
Join the World of Zero Discord Server: discord.gg/hU5Kq2uUsing Scriptable Objects in UnityWorld of Zero2023-04-08 | `ScriptableObject`'s are a way to make configurable objects you can attach to `MonoBehavior`'s or others objects. This allows you to quickly create and swap out data on your game objects without having to create and manage entire object Prefabs. You can use this to manage things like enemy health, weapon stats or character behaviors.
Join the World of Zero Discord Server: discord.gg/hU5Kq2uAutomatically Processing Assets with Custom Unity Asset PipelinesWorld of Zero2023-02-11 | Continuing our journey of adding the ability to easily use SVG assets in Unity, today we're going to be exploring how to automatically process and convert SVGs to PNGs whenever one is added to our Unity project.
In order to handle Unity asset import events we need to create an `AssetPostprocessor` by creating a custom class that inherits from the class. Once that's done we can extend our custom Asset Processing using the provided methods from Unity. A list of those is available here: docs.unity3d.com/ScriptReference/AssetPostprocessor.html
The `AssetPostprocessor`'s `OnPostprocessAllAssets` function is called when the Assets imported into your project have changed. In this case, if we move, delete or add new assets this is the message that will be invoked for us to hook into those changes and run our custom Asset processing.
The code I'm using expects Inkscape to be on your PATH. If you don't have Inkscape installed you can download it here: inkscape.org/release/. If Inkscape is correctly configured you should be able to run `inkscape --help` in your terminal and get a valid response.
Join the World of Zero Discord Server: discord.gg/hU5Kq2uBuilding a Cloud Game w/ @MicrosoftReactor - Day 3World of Zero2022-12-29 | Grab a controller and brush off your C# skills - we're building a game this week! Over the next 3 days (Tuesday - Thursday 11-3 Pacific) we'll be diving into Unity and building a game that we can connect up to the cloud to explore building cloud connected games.
This stream is also available on the Microsoft Developer and Microsoft Reactor Channels:
Join the World of Zero Discord Server: discord.gg/hU5Kq2uBuilding a Cloud Game w/ @MicrosoftReactor - Day 2World of Zero2022-12-29 | Grab a controller and brush off your C# skills - we're building a game this week! Over the next 3 days (Tuesday - Thursday 11-3 Pacific) we'll be diving into Unity and building a game that we can connect up to the cloud to explore building cloud connected games.
This stream is also available on the Microsoft Developer and Microsoft Reactor Channels:
Join the World of Zero Discord Server: discord.gg/hU5Kq2uBuilding a Cloud Game w/ @MicrosoftReactor - Day 1World of Zero2022-12-28 | Grab a controller and brush off your C# skills - we're building a game this week! Over the next 3 days (Tuesday - Thursday 11-3 Pacific) we'll be diving into Unity and building a game that we can connect up to the cloud to explore building cloud connected games.
This stream is also available on the Microsoft Developer and Microsoft Reactor Channels:
Join the World of Zero Discord Server: discord.gg/hU5Kq2uBuilding a Cloud Game w/ @MicrosoftReactor - Day 2World of Zero2022-12-27 | Grab a controller and brush off your C# skills - we're building a game this week! Over the next 3 days (Tuesday - Thursday 11-3 Pacific) we'll be diving into Unity and building a game that we can connect up to the cloud to explore building cloud connected games.
This stream is also available on the Microsoft Developer and Microsoft Reactor Channels:
Join the World of Zero Discord Server: discord.gg/hU5Kq2uTracking Task Progress in UnityWorld of Zero2022-12-24 | Let's start expanding on the SVGs in Unity project we started that converts SVG's into an image format that is usable by Unity (youtube.com/watch?v=dnDz4lVbMWw) by moving the process into a background process we can track using the new Unity Progress API.
The Progress API allows us to create a progress tracker that displays the progress of long running background tasks in Unity without blocking the user while they run. This can be used to track Tasks you might run like our SVG renderer and also gives us a way to provide a feature for the user to cancel the task mid-execution.
The Unity Progress API works through a series of static methods that track Progress by a unique identifier (an `int`). These identifiers are how you can track a task over time. For example:
We can add additional features to this as well including children tasks, step tracking, pausing and canceling tasks as well. We explore some of those throughout the implementation of the features for my own SVG generator in this video, but you can also find out a lot more about all of the features available to you in the Progress API documentation on the Unity website.
I was suggested to checkout the Progress API by Jason Storey, you can find his channel with loads of other helpful Unity and Game Dev tips at youtube.com/c/JasonStorey
Join the World of Zero Discord Server: discord.gg/hU5Kq2uGenerating Images from SVGs with Unity and InkscapeWorld of Zero2022-12-23 | Often when building a project you'll need to do some sort of repetitive task as part of the work. This can be things like data entry, running a script or other jobs. We can use software to automate some of this work to help save ourselves time and remove the potential slowness of doing things manually. Additionally, this kind of automation can ensure that jobs complete with consistent results with less opportunity for human error. Today we're going to dive into an implementation of a quick tool to help us convert SVG's (which Unity can't natively render) into PNG's automatically so we can take advantage of SVG based icon packs or designs and the scalability of SVG's while still being able to view and use the art inside of Unity.
In order to do this we're going to create a Unity [`MenuItem`](docs.unity3d.com/ScriptReference/MenuItem.html) that launches the Inkscape CLI to automatically render images from SVG files in our directory.
The code for this task looks like this:
```csharp // Search the projects Assets directory and all children directories var searchDirectory = Path.Combine(Environment.CurrentDirectory, "Assets"); Debug.Log($"Searching for SVGs in {searchDirectory}"); var svgFiles = Directory.EnumerateFiles(searchDirectory, "*.svg", SearchOption.AllDirectories); foreach (var svgFile in svgFiles) { // Generate a new path with a PNG extension instead of the original SVG extension - reusing other parts of the path var pngFile = Path.ChangeExtension(svgFile, "png"); Debug.Log($"Converting {svgFile} to {pngFile}"); Process process = Process.Start("inkscape", $"-o {pngFile} -w 32 -h 32 {svgFile}"); //32 is the size in pixels of the width and height of the generated image process.WaitForExit(); } Debug.Log("jobs done"); ```
The icons I'm using are from the Material Design Icons set, you can browse the complete set of icons here: materialdesignicons.com
Join the World of Zero Discord Server: discord.gg/hU5Kq2uBuilding a Website in C#World of Zero2022-12-17 | Working on some Blazor website projects. Come and chat!Turning OpenSCAD Files into STL Meshes with GitHub ActionsWorld of Zero2022-11-28 | OpenSCAD is a tool that allows you to program CAD models using its custom programming language rather than dragging and dropping models in an editor. This allows you to define your designs entirely in code that can be compiled into rendered images or 3D models. Let's explore how we can connect that compilation feature to GitHub actions so we can automatically create new models whenever code is edited in our design.
To do this we'll be taking advantage of GitHub Actions and using that to open Pull Requests with the updated models as STL files that we can review and merge into our code. We can take advantage of GitHub's built-in STL viewer in order to preview models directly in any web browser.
Because we are only using features natively included in GitHub we can also use this as a full development loop so we can edit and regenerate models anywhere where we can access GitHub including things like a phone by using tools like http://github.dev/!
If you missed the first video introducing OpenSCAD you can watch that here: youtu.be/HxiyUi4RQzw
Join the World of Zero Discord Server: discord.gg/hU5Kq2uRedesigning our C# Scripting in Unity ToolWorld of Zero2022-11-19 | ...Using Git HooksWorld of Zero2022-11-12 | Git Hooks provide a way for you to hook into your local git installation and attach additional behavior to common git actions. For example: validating that your code builds during a commit, confirming git commit messages or running your test suite before pushing your code changes to your peers. Because git hooks run on your local machine and are not checked in with the rest of your code you can also use them to automate certain parts of your workflow that might be unique to you.
Note: Git Hooks are not a replacement for a CI/CD pipeline like GitHub Actions, CircleCI etc!
You can add a new Git Hook by adding a file to the `.git/hooks` directory of your project that matches one of the supported git hooks. The supported git hooks are:
You can find [more about what each of these git hooks do in the Git documentation](git-scm.com/book/en/v2/Customizing-Git-Git-Hooks). Some of these may not be helpful if your doing local development with an existing remote repo somewhere like GitHub or GitLab.
Files you change in the `.git` directory will not be checked into your git repository and therefore will not be visible to the rest of your team. If you'd like to share your pre-commit and other hooks with your team you can place the scripts somewhere inside your project and create a symlink to them in the `.git/hooks` directory.
Note: make sure that you make your Git Hooks executable or git will not be able to access and run them!
If you'd like to be able to edit `.git` files more easily inside of Visual Studio Code you'll need to disable the automatic file exclusion. You can do this by updating your `settings.json` file by adding the following setting:
This setting prevents all `.git` directories in your project - regardless of where they are located - from being hidden.
You can also bypass Git Hooks using the `--no-verify` (shorthand `-n`) argument when running git commands in your CLI. This will completely bypass these hooks and prevent them from running. If you have a Git Hook that requires tests to pass before pushing running `git push --no-verify` would allow you to push your changes for example.
Join the World of Zero Discord Server: discord.gg/hU5Kq2uUsing Dependency Injection in ASP.NETWorld of Zero2022-10-20 | Dependency Injection is a tool we can use to automatically provide objects with services they need without having to explicitly declare what is needed inside of the objects themselves. This allows us to more easily reconfigure objects to fit our needs and allows us to adopt our code more easily to the environments we're running it in. Dependency Injection is a form of the inversion of control (IoC) software design pattern.
In our example we're injecting an `ICalculator` into our application and implementing that with `Calculator`:
```csharp public interface ICalculator { int Value { get; } void Operation(int number); }
public class Calculator : ICalculator { public int Value { get; private set; } public void Operation(int number) { Value += number; } } ```
There are three scopes you can use when adding services to inject into your code:
If you're interested in using Dependency Injection in Spring Boot and Java you can learn more about that here: youtu.be/EsbMbg34CpQ If you're interested in learning more about how to use Dependency Injection in your Unity games you can learn more about that here: youtu.be/e0KWsizPYAw
***
Join the World of Zero Discord Server: discord.gg/hU5Kq2uDetect Objects in Your Camera View - Unity Geometry UtilitiesWorld of Zero2022-10-18 | Let's explore how you can detect when an object is inside the players camera view by using the camera's frustum and axis-aligned bounding boxes (AABB). This takes advantage of Unity's built in [`GeometryUtility`](docs.unity3d.com/ScriptReference/GeometryUtility.html) class that provides some helper functions to make this easier.
The first thing to do is define a set of planes we can use to describe the view of our camera. This is called a frustum and is the white box-like gizmo you see in Unity's scene editor when you select a `Camera`. The frustum defines your cameras view and we can take advantage of this to test if objects are inside or outside of the bounds we calculate.
In order to calculate the frustum planes we'll want to run `GeometryUtility.CalculateFrustumPlanes(...)` and pass in the camera we want to calculate the Frustum of. In our quick example we'll use `Camera.main` to grab the main camera in our scene.
Once we've calculated the camera frustum planes we can provide those to the `GeometryUtility.TestPlanesAABB(...)` method to test if the bounding box we provide is inside or outside of the planes we calculated earlier. This method returns true if the bounding box provided overlaps with or is inside of the `Plane[]` boundaries. In this case we're testing if a bounding box overlaps or is inside of the camera's viewport.
To get the bounds of an object you can use the `Collider.bounds` field. This calculates a world space axis-aligned bounding box for the collider and returns it to you so you can reference it in your object. The bounds are always a box aligned to the XYZ planes but are supported on all types of `Collider` in Unity.
Once you've passed your bounds into the test function you can use that to perform your behavior for objects in or out of view. This can be used to freeze objects when they come into view (like the Doctor Who Angels) or to move/delete an object when it gets out of sight (like some gibs you only want to be cleaned up when the player looks away). There's a lot of different uses for functions like this!
The code I'm using in this example has an `Update` that looks like this:
Join the World of Zero Discord Server: discord.gg/hU5Kq2uLets Explore Global Usings in C# 10World of Zero2022-10-17 | Global usings are a [new feature in C# 10](learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10#global-using-directives) that give you the ability to declare a using directive over every source file in your project instead of needing to duplicate the declaration inside of each file in your projects! This can help you reduce the duplicated code in your projects and make commonly used libraries and namespaces more readily available across your project!
To use a global using you can add `global` before your using statements like this statement you might use in a data serializing/deserializing library:
```csharp global using Newtonsoft.Json ```
Including a global using will cause the compiler to include the namespace when resolving types across the entire compilation of your project instead of scoping that reference to the file the using is a part of. What this typically means is that you will want to use this for common namespaces used across your project and continue using file based using statements when referencing more feature specific types.
Global Usings are also part of the `ImplicitUsings` feature you might see in your `.csproj` files. To learn more about this feature you can watch this video! youtu.be/NlvhBpLl0DY
This videos thumbnail uses a globe SVG from here: commons.wikimedia.org/wiki/File:Emojione_BW_1F30E.svgLets Explore Implicit Usings in C# 10World of Zero2022-10-17 | Implicit usings is a feature in .NET that allows you to have the compiler automatically add [global usings](youtu.be/z4THCW3b16k) to your projects for common namespaces used in projects of the type you've chosen. This can help you get started more quickly in .NET by automatically importing common namespaces like `System` and `System.Linq` without you having to explicitly declare them somewhere in your projects.
You can turn on Implicit Usings in your .NET 6 projects by adding this line to your Project file.
Implicit Usings introduce namespaces into the global space. You can learn more about how to add your own custom namespaces here by using `global` usings: youtu.be/z4THCW3b16k
Note: You can always check which implicit usings are being generated for your project by navigating to your projects `obj` directory and finding the generated file named: `[Your Projects Name].GlobalUsings.g.cs`.
Join the World of Zero Discord Server: discord.gg/hU5Kq2uUsing .NET Interactive and Jupyter NotebooksWorld of Zero2022-08-27 | Today we're exploring .NET Interactive and how you can use it inside of Jupyter Notebooks to run and document code samples alongside markdown documentation. This can be a really handy way to create and share example code and snippets in an interactive way that allows you to just change code and run it inside of the document the code is embedded in.
Jupyter Notebooks are a tool that is part of [Project Jupyter](jupyter.org) a project for creating an interactive data notebook. It's extremely common among data scientists and python programmers as a way to document an AI model and show the data that is being worked on. We are able to take advantage of that same platform and provide a .NET runtime (.NET interactive) that allows us to compile and run .NET code in these notebooks. This gives us access to many of the same features while allowing us to write our code in C# or another .NET language.
Join the World of Zero Discord Server: discord.gg/hU5Kq2uI Built a Tool That Turns GitHub Contributions into Bookmarks Heres How It WorksWorld of Zero2022-07-10 | Inspired by GitHub Skyline I've built a tool you can run from the command line that generates a bookmark from your GitHub Contributions. The SVG the tool generates can be 3D printed or laser cut to create a physical bookmark you can take with you! In this video we'll walk through how you can use the tool yourself by creating a Personal Access Token to gain access to the GitHub API.
To create a Personal Access Token on GitHub navigate to your Profile, select Developer Settings and Access Tokens. Create a token with the minimum number of permissions required for the app you are trying to use. **Do not share your Personal Access Tokens publicly** because people with these tokens will be able to perform the selected actions as if they were you!
I currently run events out of the Microsoft Reactor in San Francisco as well! If your nearby and want to learn things or join a workshop in person checkout our meetup group. meetup.com/Microsoft-Reactor-San-Francisco
Join the World of Zero Discord Server: discord.gg/hU5Kq2uUsing C#s nameof Expression - C# Quick TipWorld of Zero2022-07-10 | The `nameof` expression allows you to convert a variable, property, type or function into a string that represents its name. This can be an alternative to typing out strings directly in your code when you need to reference the name of an object in your code. This is really common when implementing `INotifyPropertyChanged` events and has a number of other uses as well.
The advantage of using `nameof` compared to writing out the object in a string is that the dotnet compile will fail if the reference in your nameof expression does not exist. This can help catch issues during refactoring when elements are renamed. Typically, when using strings directly those references can become runtime errors and potentially be very difficult to identify (ex. a UI element not updating because it no longer receives its Property Update notification). `nameof` can help avoid that issue in your code.
Some examples of how to use `nameof`:
```csharp class Program { public float aVariableNamedFoo = 3.14f; public float Foo =˃ aVariableNamedFoo;
Join the World of Zero Discord Server: discord.gg/hU5Kq2uSending Real-Time Messages to Unity from a Blazor Website - SignalR in Unity - Part 3World of Zero2022-07-07 | Let's complete our SignalR in Unity experiment by adding a Blazor Website to it. This will allow us to use a browser to send messages directly to Unity to create updates instead of either needing to install a Unity game or run a console app. We'll quickly cover some of the components in a Blazor website as well as how some of the architecture works.
We'll take a quick detour to chat about Blazor Web Assembly (Blazor WASM) vs Blazor Server because I completely forgot what project template I chose when setting up this test project. 😅
The architecture of our app looks like this:
```mermaid graph LR A[Browser App] --˃ B[Blazor Server] B--˃A B --˃ C{ASP.NET SignalR Server} C --˃|Sends Updates to| D[Unity] E[Console App] --˃ C ```
You can create a new Blazor project using either:
### Blazor Web Assembly
```sh dotnet new blazorwasm ```
or
### Blazor Server
```sh dotnet new blazorserver ```
If you want to learn more about Blazor you can get started here: https://aka.ms/getstartedwithblazor
***
If you would like to get started learning SignalR you can learn more at https://aka.ms/getstartedsignalr
My previous SignalR series shared at the [Microsoft Reactor](youtube.com/c/MicrosoftReactor1) where we created an interactive canvas you could collaboratively draw on with the rest of the world!
You can see some of the other content I have planned outside this channel in the Microsoft Reactor (and even come to our in-person events) at the [Microsoft Reactor San Francisco Meetup Page](meetup.com/Microsoft-Reactor-San-Francisco/).
***
Join the World of Zero Discord Server: discord.gg/hU5Kq2uAdding Unity Support - SignalR in Unity - Part 2World of Zero2022-07-06 | The next part of this experiment is integrating Unity with the rest of our SignalR components so that they can communicate with one another. The goal here is to send a message from our console app to an ASP.NET server which responds by forwarding that message to our Unity project. This will give us a way to send data between multiple different applications and render those changes inside of our Unity game.
This initial project is intended just to validate that the entire workflow just works. That Unity and our SignalR server can connect with one another. Later we can turn this capability into a cool game, for example enabling a party game where everyone plays from their phone. For now, though we're just testing out the limits of what all of this actually enables.
If you would like to get started learning SignalR you can learn more at https://aka.ms/getstartedsignalr
My previous SignalR series shared at the [Microsoft Reactor](youtube.com/c/MicrosoftReactor1) where we created an interactive canvas you could collaboratively draw on with the rest of the world!
You can see some of the other content I have planned outside this channel in the Microsoft Reactor (and even come to our in-person events) at the [Microsoft Reactor San Francisco Meetup Page](meetup.com/Microsoft-Reactor-San-Francisco/).
***
Join the World of Zero Discord Server: discord.gg/hU5Kq2uReal-Time Messaging Between Console Apps with SignalR - SignalR in Unity - Part 1World of Zero2022-07-05 | We're starting a new project beginning with an introduction to SignalR. Our goal is to introduce SignalR into a Unity project so we can communicate in real-time between a Unity game and a web app. In this video we'll introduce SignalR, an open-source (github.com/SignalR/SignalR) library that allows us to create a client server communication system in our apps enabling them to send messages back and forth between clients.
If you would like to get started learning SignalR you can learn more at https://aka.ms/getstartedsignalr
My previous SignalR series shared at the [Microsoft Reactor](youtube.com/c/MicrosoftReactor1) where we created an interactive canvas you could collaboratively draw on with the rest of the world!
You can see some of the other content I have planned outside this channel in the Microsoft Reactor (and even come to our in-person events) at the [Microsoft Reactor San Francisco Meetup Page](meetup.com/Microsoft-Reactor-San-Francisco/).
***
Join the World of Zero Discord Server: discord.gg/hU5Kq2uExploring MAUI - Multiplatform Apps Built With .NETWorld of Zero2022-06-12 | .NET MAUI is an open-source framework for building multiplatform user interfaces that can reuse code across iOS, Android, MacOS and Windows! Let's dive into .NET MAUI and try to build a to-do app from scratch - learning what's new along the way as I build my first .NET MAUI app.
Let's explore how to layout our own UI with XAML, figure out how to setup a view model and data bind our UI to it and create our own custom commands to invoke. We'll build an app that uses the exact same C# code to write a native app we can test on both Windows and .NET.
***
Brandon Minnick and I discussed the architecture and how MAUI works a bit more in this video: youtube.com/watch?v=aUaqgTn2hQk
Looking for an easier way to integrate with MAUI? Check out the MAUI Community Toolkit which has a ton of cool tools to make writing MAUI code easier! github.com/CommunityToolkit/Maui
Some of the graphics in the thumbnail are 3D models by Kenney at https://www.kenney.nl/
Join the World of Zero Discord Server: discord.gg/hU5Kq2uHandling 3rd Person Camera Physics with SphereCastsWorld of Zero2022-06-04 | Hello again internet! Let's dive into how to manage camera physics in your third person cameras using `SphereCast`s.
`SphereCast`'s expand upon what you might know about raycasts projecting a beam through your scene that can detect physical objects in the scene and let you know if it's hit them. Unlike a raycast though a `SphereCast` includes a radius. This can prevent the detection from going through tight spaces or between closely aligned Game Objects.
To showcase this, we're going to build a quick 3rd Person Camera in a scene that has some narrow alleyways. In order to prevent our camera from clipping geometry inside those alleyways and to prevent it from ending up in a narrow space we'll project a sphere using a `SphereCast`. This gives our camera some safety and improves the quality of the camera positioning.
The code we wrote in this video is here if you'd like to try it yourself!
```csharp using UnityEngine;
public class ThirdPersonCamera : MonoBehaviour { public float cameraSpeed; public Transform cameraTransform; public float cameraDistance; public float radius = 0.25f;
void Update() { // Multiplying quaternions adds them together this.transform.rotation *= Quaternion.Euler(0, cameraSpeed * Input.GetAxis("Mouse X"), 0);
// Move Camera back until we get near a Physics Collider Ray ray = new Ray(this.transform.position, -this.transform.forward); RaycastHit hit; if (Physics.SphereCast(ray, radius, out hit, cameraDistance)) { cameraTransform.localPosition = Vector3.back * hit.distance; } else { cameraTransform.localPosition = Vector3.back * cameraDistance; } }
// Draw a Gizmo around where the camera has been projected to. void OnDrawGizmos() { Gizmos.color = Color.blue; Gizmos.DrawWireSphere(cameraTransform.position, radius); } }
I currently run events out of the Microsoft Reactor in San Francisco as well! If your nearby and want to learn things or join a workshop in person checkout our meetup group. meetup.com/Microsoft-Reactor-San-Francisco
Join the World of Zero Discord Server: discord.gg/hU5Kq2uExploring How to Write Custom Pixel Shaders for the Windows TerminalWorld of Zero2021-10-06 | The Windows Terminal is a new terminal for Windows that allows you to run PowerShell, Command Prompt, the Azure Command Shell or any other terminal environment. One of the cool experimental features it includes is the ability to run a custom DirectX pixel shader when rendering the terminal. This can allow you to customize your prompt and create cool visual effects in your Terminal. Let's explore how you can configure and create your own shader for the Windows Terminal!
To use a shader you will need to update your Windows Terminals `settings.json` file to point to a DirectX pixel shader file. The setting is called "experimental.pixelShaderPath" and is located in your terminals "profiles". In this example we'll be applying the shader to every profile in our terminal by default by updating our settings file like this:
```diff "profiles": { "defaults": { ... + "experimental.pixelShaderPath": "The absolute path to our shader.hlsl", } } ```
A basic shader that just rerenders the sampled terminal input might look like this:
It includes a `shaderTexture` which is a Texture that contains the rendered content of the Terminal prior to your shader being applied. This means it will include the colored text but none of your effects. A `samplerState` is also provided which provides state information about sampling the texture.
The shader requires a `main` method that returns a four dimensional vector containing the red, green, blue and alpha channels to render. A transparent result will render the background of your terminal profile.
To modify the behavior of the shader, change the results returned from the `main` method to match your desired outcome and update the Windows Terminal. You should be able to see the results of your changes. For example our shader that only renders the red channel of our terminal has a `main` method that looks like this:
That README includes additional information including how to access the `PixelShaderSettings` which provide information such as a `Time` variable to create animated effects!
***
If you'd like to add a shortcut that can toggle shader effects on or off then you can add an action to your Windows Terminals `settings.json` file. In the `actions` block add an entry for `toggleShaderEffects` like this:
You can find some additional examples of Windows Terminal shaders here: github.com/Hammster/windows-terminal-shaders My pride flag Windows Terminal shader is located here: worldofzero.com/posts/pride-windows-terminal Join the World of Zero Discord Server: discord.gg/hU5Kq2uCreating a Quick Custom Profile in the Windows TerminalWorld of Zero2021-10-06 | The Windows Terminal allows you to run any number of different profiles. Some of the defaults that you might see pre-configured include things like PowerShell and Command Prompt, but you can introduce your own profiles to the Windows Terminal to fit your needs! This means you can add your favorite cloud shell or add a custom shell like NuShell directly to the Windows Terminal so they can be launched immediately with a hotkey or via the GUI. In this video we'll look at how you can quickly add a new profile to the Windows Terminal
There are multiple ways the new profile can be introduced. In this video we'll be duplicating an existing profile and configuring it to automatically SSH into one of my development servers. This can be done by opening the Windows Terminal settings and clicking "Add a New Profile" from the options on the left hand side of the settings screen. That button will present you with the option to either duplicate an existing profile or add a new empty profile. Duplicating a profile will automatically copy style, icon and other settings.
If you prefer to work directly with configuration files you can manually edit your Windows Terminal profiles in the `settings.json` file. This can be accessed by clicking "Open JSON file" from the settings menu.
Your profiles are configured in a list under the "profiles" setting. Add your new profile to that list and save the file to begin using it!
Join the World of Zero Discord Server: discord.gg/hU5Kq2uCreating a Stepped Gradient Shader in UnityWorld of Zero2021-07-20 | Let's build a stepped gradient in Unity! This is a form of gradient with hard transitions between the different keyframes in the gradient which creates clear blocks of color like you might see on a flag or logo. To do this we'll take advantage of the `lerp` and `step` function.
The `lerp(x, y, s)` function takes 3 arguments and standards for linear interpolation. This means a constant transition occurs between the left-hand side (`x`) and right-hand side (`y`) as the value (`s`) moves between 0 and 1. For example: `lerp(0, 10, 0.5)` will return `5`.
The `step(l, r)` function takes 2 arguments and returns either 0 or 1 depending on if the left-hand side (`l`) is greater than the right-hand side (`r`). For example `step(5, 1)` will return `0` because `5` is greater than `1`, if the arguments are reversed `step(1,5)` would return `1`.
We can use this behavior to define our gradient. Each "key" in the gradient can be represented as a `step` function that either selects the new value in the gradient or returns the original values. The `lerp` function can provide that color selecting option by providing the color states as the left and right arguments in the `lerp`.
Here is an example of the 3 color gradient fragment shader we built:
```shader // This example code is for a Unity unlit shader fixed4 frag (v2f i) : SV_Target { // Create a gradient transitioning between three colors (red, green and blue). float4 result = float4(1, 0, 0, 1); // red from 0 to 0.33 result = lerp(result, float4(0, 1, 0, 1), step(0.33, i.uv.x)); // green from 0.33 to 0.67 result = lerp(result, float4(0, 0, 1, 1), step(0.67, i.uv.x)); // blue from 0.67 to 1.0 return result; } ```
Here's an example of what this shader technique might look when applied like a flag:
I've explored step and smoothstep in more depth in this video: youtu.be/-vGNd8pnbYs Join the World of Zero Discord Server: discord.gg/hU5Kq2uSupporting Grid Rendering - LINQ for Unity - Part 3World of Zero2021-07-17 | Unity's Editor UI does not support rendering elements in a grid. For some elements like Textures, Meshes and Materials rendering the results in a vertical list does not use the space of the LINQ for Unity editor view very effectively so a grid-based view could provide a much more concise and cleaner UI. Let's implement a way to draw these components in a Grid!
Unity's Editor UIs can expand and scale in two dimensions either vertically or horizontally. We want to create a horizontally wrapping grid, this means the grid will add elements adjacent to one another horizontally so long as extra space is available. Once no more space is available in the row we create a new row and continue adding new elements to that new row. This approach will allow the grid to expand vertically without introducing a horizontal scroll.
For our implementation we're going to be using uniformly sized grid elements. This means that every element in the grid will take up the same amount of space. Doing this prevents creating any complex layout situations (and potentially having to solve the 2D napsack problem).
***
You can find more World of Zero content at worldofzero.com or catch my streams at twitch.tv/worldofzerodev Join the World of Zero Discord Server: discord.gg/hU5Kq2uUsing AnimatedValues in Custom Unity EditorsWorld of Zero2021-07-11 | When working with the Unity editor it can be useful to animate the movement of a value from one place to the next. Unity provides a series of classes you can use in the editor to help accomplish that. These classes will linearly interpolate from their current value to the target value you've given them. This can be used to smoothly move the camera in your scene or take advantage of the animated `EditorLayout.BeginFadeGroup` in an intuitive way - a control that can collapse and expand on itself using the value of a float.
These classes have a variety of values.
* `speed`: This effects how quickly the AnimatedValue transitions to the `target` value. * `target`: The target of that the AnimatedValue is transitioning towards. * `value`: The current value of the object. * `valueChanged`: This is an event handler that is invoked when the AnimatedValue is transitioning between values. This can be used to trigger Editor GUI Repaint's or react to the animation in other ways.
One example of using this in an editor is to initialize and add a listener to automatically `Repaint` during an update. Unity does not redraw the editor window on a consistent basis and needs to be "Repainted" in order for the updates to show. Interactions like moving the window or interacting with your mouse can trigger Repaints, but since we're trying to animate an object in our UI, subscribing to the `valueChanged` event allows us to ensure a smooth appearance.
```csharp animatedField = new AnimBool(false); animatedField.valueChanged.AddListener(Repaint); ```
The value of the `AnimBool` can be retrieved using the `animatedField.faded` property. This is a special property of animated boolean values that returns a floating point representation of the boolean animation. The value will be between 0 (`false`) and 1 (`true`).
These classes are part of the UnityEditor library and are not available in your compiled game. For that you'd need to implement a class that provides the functionality you need.
Join the World of Zero Discord Server: discord.gg/hU5Kq2uDemoing the Tool and Adding Command History - LINQ for Unity Stream - Part 2World of Zero2021-07-09 | Another VOD from the World of Zero Twitch development stream. This is a demo of some of the work that's happened on the LINQ for Unity tool behind the scenes and also covers introducing command history so that we can track queries run against the tool and quickly rerun them.
***
You can catch the development streams for this tool live on Twitch at twitch.tv/worldofzerodev Join the World of Zero Discord Server: discord.gg/hU5Kq2uImproving Object References - LINQ for Unity Stream - Part 1World of Zero2021-06-24 | LINQ for Unity is a new tool I'm building that allows you to run C# queries, typically LINQ, that you can then use to modify objects in your scenes easily. This allows you to select all of the Colors of your scenes Lights for example and easily edit them all or quickly change the positions of objects that meet a certain criteria.
One of the challenges the tool is currently facing is handling value types. These are common in Unity and occur when any primitive types (like `float`, `int`) or any structs (like `Vector3`, `Color`) are used. Instead of reference types which point to the location of data a value type will copy data when it is assigned. This means that if we try to select all of an objects positions that we will only retrieve the **values** of those positions. These values are read-only and if we do change them they will not effect the Transform they are a member of.
In this stream we will be designing, prototyping and building a solution to this value type problem using reflection and exploring other alternatives.
This is from a Live Stream I did on Twitch! You can follow me there to get notified the next time I go live: twitch.tv/worldofzerodev Join the World of Zero Discord Server: discord.gg/hU5Kq2uBuilding a Tree-Based Calculator in C#World of Zero2021-05-27 | Let's explore a calculator that can solve a variety of equations dynamically. We'll be able to use this solution to explore tree data structures and specifically the use of binary trees to represent and solve common math problems.
A binary tree is a data structure which represents a set of relational data in a series of nodes. Each node may have at least one **parent node** and is linked to up to two **children nodes**. The node at the beginning of the tree has no parents and is called the **root node**. The nodes at the ends of the tree have no **children nodes** and are called **leaf nodes**.
For our solution we will be creating a tree where each **leaf node** contains an integer value (like 2, 5 or 42). The nodes higher up in the tree will contain various formula that can calculate a new integer value from their **children nodes**. Using this method we can iterate over the entire tree to solve for the value at the **root node**, that value is the result of our equation.
We can turn the equation `2 * (3 + 5)` into a tree that looks like this:
```mermaid graph TD; a(*) b(2) c(+) d(3) e(5)
a--˃b a--˃c c--˃d c--˃e ```
Then we can attempt to solve for the value of any unknown node in the tree by evaluating the node's function with the left- and right-hand values from the children. This will allow us to identify that `2 * (3 + 5)` is `16`. This is a small example but now that we have defined the algorithm for solving these equations, we're able to parse and solve these problems automatically no matter how complex they grow to be.
var calc = new Calculation() { LeftHandValue = new Calculation() { CurrentValue = 2 }, RightHandValue = new Calculation() { LeftHandValue = new Calculation() { CurrentValue = 3 }, RightHandValue = new Calculation() { CurrentValue = 5 }, Function = (left, right) =˃ left + right }, Function = (left, right) =˃ left * right }; var result = Solve(calc); Console.WriteLine($"2 * (3 + 5) = {result}!");
int Solve(Calculation calc) { if (calc.CurrentValue.HasValue) { return calc.CurrentValue.Value; } if (!calc.LeftHandValue.CurrentValue.HasValue) { calc.LeftHandValue.CurrentValue = Solve(calc.LeftHandValue); } if (!calc.RightHandValue.CurrentValue.HasValue) { calc.RightHandValue.CurrentValue = Solve(calc.RightHandValue); } calc.CurrentValue = calc.Function(calc.LeftHandValue.CurrentValue.Value, calc.RightHandValue.CurrentValue.Value); return calc.CurrentValue.Value; }
public class Calculation { public Calculation LeftHandValue { get; set; } public Calculation RightHandValue { get; set; } public int? CurrentValue { get; set; } public Func˂int, int, int˃ Function { get; set; } } ```
***
I've explored Top-Level Programs more here: youtu.be/uxxROAx6MMU An intro to `dotnet watch`: youtu.be/nYudqdL55us Join the World of Zero Discord Server: discord.gg/hU5Kq2uImplementing Scene Switching - An Elevator Between Scenes - Part 2World of Zero2021-04-23 | Continuing our elevator and asynchronous scene management system development let's try to build a 3-scene system that will allow us to create a base scene with the global game objects (our player, scene transition elevator, camera etc) and the two "floors" we'll be transitioning between.
Our goal is to unload the currently loaded floor (if one is loaded) and replace it with the new scene before opening the elevator to reveal the changed scene. If we were to reverse this order or tried to unload and load the scenes simultaneously, we could end up in a situation where both of our playable scenes were loaded at the same time. For a completely static scene this is probably fine, but any dynamic objects like physics, ai etc could potentially attempt to interact with the other scene and cause behavior we don't want.
The flow we're trying to create with this effect should look something like this.
```mermaid graph LR B(Try to load First Floor) C(Close Elevator Door) D{Is A Floor Loaded Already?} E(Unload Loaded Floor) F(Load First Floor) G(Open Elevator Door) B--˃C C--˃D D-- Yes --˃E D-- No --˃F E--˃F F--˃G ```
***
The [**Elevator Between Scenes** series playlist](youtube.com/playlist?list=PLEwYhelKHmigCVDWNM5--f7PofdkvXbuZ) Join the World of Zero Discord Server: discord.gg/hU5Kq2uLets Make a Lazy String Parser in C#World of Zero2021-04-21 | Let's create a quick string parsing script that can read a long string and return a delimited set of results (we'll be finding words). We can use this to iterate through every word in the string until we find the value we are looking for without having to pre-process the entire original string.
A lazily evaluated function is one that calculates the results of the function as the values are requested. In this case it means we can create a set of integers or strings that we generate dynamically without having to first fill an array or other data structure with all the data first. This also means that for large data sets where we will stop iterating early in the list that we can process only parts of the provided data.
C#'s `yield` keyword allows us to return a value from a function and then continue from that point in our code on the next iteration. This allows us to iterate through a loop and `yield` results from the inside of the loop to expose new data to the calling function before generating the complete list. Instead, our list is generated procedurally from the code in our function.
Using `yield` we can generate a lazily calculated set of values from an infinite loop.
```csharp public static IEnumerable˂int˃ PositiveIntegers() { for(int i = 1; i ˂ int.MaxValue; ++i) { yield return i; } }
// We can print the first ten elements in the set of positive integers without // looping through the complete set of integers. public static void Main(string[] args) { foreach(var number in PositiveIntegers().Take(10)) { Console.WriteLine(number); } } ```
To create our lazy string parser we'll use the concepts above but introduce a few extra steps. We're going to step through an input string character by character to form words. When a delimiter character is found we'll yield the word we've found so far and then reset that word. When the next word is queried from the `IEnumerable` we'll repeat the process. This will keep going until we stop iterating over the `IEnumerable` result of the function or we reach the end of the function.
Our lazy string parser implementation looks like this:
```csharp public static IEnumerable˂string˃ Parse(string content, char delimiter) { var word = String.Empty; foreach(var character in content) { if (character == delimiter) { if (word != String.Empty) { var result = word; word = String.Empty; yield return result; } } else { word += character; } } yield return word; } ```
The thumbnail of this video includes a modified image of [Duke Humfrey's Library](commons.wikimedia.org/wiki/File:Duke_Humfrey's_Library_Interior_3,_Bodleian_Library,_Oxford,_UK_-_Diliff.jpg). This file is licensed under the [Creative Commons Attribution-Share Alike 3.0 Unported](creativecommons.org/licenses/by-sa/3.0/deed.en) license.Using Generic Type Aliases in C#World of Zero2021-04-20 | C# includes a feature that allows you to use the `using` keyword to define aliases for different types or namespaces in your code. This can allow you to provide explicit names for generic types you might reuse often so they are more understandable or easier to type. The feature creates a **generic type alias** that you may use in the place of the full type name.
For example, we can define and use a `List` of `string`s like this:
```csharp using Strings = System.Collections.Generic.List˂string˃;
Strings MakeStringList() { return new Strings() { "World of Zero" } } ```
This feature can also be used to alias namespaces to help you disambiguate classes with the same name from different namespaces without rewriting the full namespace each reference.
```csharp using Essentials = WorldOfZero.Unity.BallisticEssentials; using Sys = System;
I've uploaded other projects on my website at worldofzero.com Join the World of Zero Discord Server: discord.gg/hU5Kq2uAnimating the Elevator - An Elevator Between Scenes - Part 1World of Zero2021-04-07 | Let's start a new project that allows us to load scenes using riding an elevator as the transition. To start with we'll be building the animation controlling the opening and closing of the elevator doors. We'll be using Unity's Animation Controllers for this which means we'll be building the entire effect without writing a single line of code (or opening a code editor).
Unity's Animation Controller works like a state machine that tracks a set of properties and handles transitioning between a set of states (Animations) using transitions. We can make this state machine as complex as we'd like but for our purposes a state machine with only two states is enough to capture our goal. One state will be when the elevator doors have completely opened, and another state will represent when the doors have closed. Unity will automatically blend between animation states for us during the transition period which means that both of our animations can be a single keyframe representing the position the elevator doors should be in.
The Unity Animator Controller is documented here: docs.unity3d.com/Manual/class-AnimatorController.html Unity has published a tutorial series on learn.unity.com about using the animator controller: learn.unity.com/tutorial/animator-controllers-2019-3 Join the World of Zero Discord Server: discord.gg/hU5Kq2uUsing ContextMenu and ContextMenuItem in Unity 3DWorld of Zero2021-03-28 | There are a lot of options available to you when you want to test your project in Unity3D and validate that your code actually does what you think it does. Sometimes you just need a quick way to perform some action or access some area during development. One of the ways to introduce this into the editor is through modifications to Unity's inspector. The `ContextMenu` and `ContextMenuItem` attributes provide this option by allowing you to create menu's in the Unity inspector that can execute functions on your `MonoBehavior`s.
Some example uses of Unity 3D's `ContextMenu` and `ContextMenuItem` Attributes:
#### `ContextMenu`
A `ContextMenu` Attribute is attached to functions in your `MonoBehavior`. When that menu item is clicked it will invoke the function the attribute is assigned to:
```csharp [ContextMenu("Context Menu Example")] void HelloContextMenu() { Debug.Log("Context Menu Clicked!"); } ```
#### `ContextMenuItem`
A `ContextMenuItem` Attribute is attached to a field and requires you to provide the name of a function that will be invoked when the menu item is clicked.
```csharp [ContextMenuItem("Context Menu Item Example", nameof(InvokeContextMenuItem))] public float someVariable;
void InvokeContextMenuItem() { Debug.Log("Context Menu Item Clicked!"); } ```
[`nameof`](docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/nameof) is a C# function that returns a string representation for the name of the class, function, field, property etc that is referenced. Using this allows things like refactoring's to function better and provides compiler errors if you spell a function name incorrectly (`nameof(FunctionName)` will throw an error if `FunctionName` is not defined).
Note: The functions invoked by both `ContextMenu` and `ContextMenuItem` should not have any arguments.
***
Unity's documentation on the `ContextMenu` Attribute: docs.unity3d.com/ScriptReference/ContextMenu.html Unity's documentation on the `ContextMenuItem` Attribute: docs.unity3d.com/ScriptReference/ContextMenuItemAttribute.html Join the World of Zero Discord Server: discord.gg/hU5Kq2uLearning Async Unity Scene LoadingWorld of Zero2021-03-19 | I've been working on re-learning how to work with scenes in Unity and am planning a larger project around the feature, but wanted to bring all of you on my journey. In this video we'll be learning the basics of how to work with Unity's Asynchronous Scene Loading functions. They're extremely powerful and offer some really cool opportunities for different ways to compose your scenes that we'll be looking into in the future, but for now we'll just be focusing on the basics of how to additively load a scene using synchronous (blocking) and asynchronous (non-blocking) methods. We'll also get a chance to explore Unity Coroutines - another area I am less familiar with.
Unity references Scenes in one of two ways:
* **The Build ID of the Scene**. This can be configured in your projects Build Settings. * **The Scene Name**. This is either the file name of the scene or the full path of the scene if multiple scenes in your project have the same name.
There are two optional `LoadSceneMode`'s you can provide to Unity when loading a scene that will change how Unity handles the scene you load.
| Option | Result | | ----------- | ---------- | | `LoadSceneMode.Single` | All other loaded scenes are unloaded prior and a new scene is loaded. | | `LoadSceneMode.Additive` | The new scene is loaded alongside the already loaded scenes. |
There are different ways to load scenes asynchronously and track their progress by using an event callback on the `AsyncOperation.completed` event:
```csharp public void BeginLoadLevel() { StartCoroutine(LoadLevelAsync()); }
private IEnumerator LoadLevelAsync() { var progress = SceneManager.LoadSceneAsync("SceneName", LoadSceneMode.Additive);
while (!progress.isDone) { // Check each frame if the scene has completed. // For more information about yield in C# see: youtu.be/bsZjfuTrPSA yield return null; }
// Code after this point is executed after the new scene has loaded Debug.Log("Scene Loaded"); } ```
You can also load scenes synchronously (your game will freeze until the scene loads) by avoiding the Async versions:
Unity's documentation on using `LoadSceneAsync` is located here: docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadSceneAsync.html The `AsyncOperation.completed` event is handled in a unique way (it will always be invoked on the proceeding frame even if the scene is loaded synchronously). You may learn more about the behavior here: docs.unity3d.com/ScriptReference/AsyncOperation-completed.html Join the World of Zero Discord Server: discord.gg/hU5Kq2uQuickly Trim Video Snippets on the Command Line with FFmpegWorld of Zero2021-03-11 | FFmpeg is an open source tool that allows you to edit, encode, decode, transcode and more audio or video from your command line. This can make it a really useful tool when you need to change file formats for a video or quickly cut out parts of a video. Here we're going to look at the use case of editing a stream's intro and outro scenes from a video for YouTube. By doing this in FFmpeg instead of through my normal video editor I can avoid re-encoding the edited video. This means that the process is significantly faster. Cutting a few minutes from a multi-hour video takes only a few minutes (on my machine). This can make FFmpeg a useful addition to your video editing pipeline if you're already familiar with command line tools.
To cut a 5 minute long clip out of a larger video named `original-video.mp4` we'd run a command like:
* `-i ./source.mp4`: is used to specify an input source. In this case we're referring to a video file named `source.mp4`. * `-ss 00:05:00`: is used to set a start time offset. This will skip the amount of time specified forward in the input source and then begin the edited clip. * `-to 00:10:00`: is used to set an end time for the clip. This will cause the exported clip to only include content up to the provided time in the input source. * `-c copy`: is used to specify a codec. In this case the `copy` codec is used to help improve the speed of encoding. `copy` is a special value in `FFmpeg` that tells `FFmpeg` not to reencode your video.
Note: both `-ss` and `-to` are optional if you'd like to include content from the start or end of the source video.
Using FFmpeg to quickly trim a video is only touching the surface of what the tool is capable of. If you'd like to learn more I recommend diving into the [documentation](ffmpeg.org/documentation.html).
Explore more about FFmpeg at the official website ffmpeg.org Learn how to install FFmpeg: ffmpeg.org/download.html If you'd like to use FFmpeg for other things (like converting video snippets to GIFs) check out this blog post from GIPHY: engineering.giphy.com/how-to-make-gifs-with-ffmpeg Join the World of Zero Discord Server: discord.gg/hU5Kq2uCorrecting Lighting on our Grid Snapped Vertex Shader with Geometry ShadersWorld of Zero2021-02-20 | Lets fix our grid snapped vertex custom shader by introducing some improved lighting. Because we're manipulating our objects geometry inside our shader the normals that are used to calculate lighting are incorrect. This causes objects to appear oddly smooth and lighting effects to look very different from what you'd expect based on the geometry you see. We can't just correct the normals of each vertex because doing that would still cause the normal value to be interpolated along each of the triangles of our mesh (causing a smoothing effect). To resolve this we're going to implement a geometry shader which allows us to dynamically recreate the mesh inside our shader so we can provide data that can be tweaked to our needs.
If present a geometry shader occurs after an a vertex shader but before the fragment shader following one of these two paths:
It is not necessary for a geometry shader to recreate the same geometry that was passed in. The output can be completely modified to introduce additional information (we've used that capability in our [Grass Shader](youtu.be/b2AlyCNbYmY)). In this case our needs are simpler though, we are going to be using the geometry shader to isolate each triangle of our mesh. Doing this means that we can avoid interpolation caused by multiple triangles sharing a vertices without having to make those modification in our original mesh beforehand. This allows our shader to be compatible with any shape instead of just meshes specifically designed for this effect.
Our geometry shader recreates each triangle and assigns all the vertices of that triangle a unique normal so the face has uniform lighting. We also calculate the diffuse lighting we use inside of the geometry shader and pass that information along to the fragment shader. The geometry shader we're using looks like this (assuming our vertex shader provides world space coordinates):
By moving the grid snapping into world space positions we actually gain a few fun things! For example it means that multiple different objects with the shader applied will actually merge together cleanly in world space (in essence, all objects will share a global grid space in our scene). This makes the results a lot more consistent and prevents things like rotating or scaling an object from skewing the results. This also means that we get pretty interesting results when we apply the effect to more complex objects like a particle system, in this case we can create a series of flowing snapped cubes with particles.
Compared to the previous grid snapped shader we need to add two lines. One to move our vertices into World Space and another to move back into Object Space after our operations have been applied.
The variables I use (`unity_ObjectToWorld` and `unity_WorldToObject`) are documented here along with a number of other useful built-in shader variables: docs.unity3d.com/Manual/SL-UnityShaderVariables.html You can find a collection of other Visual Effects we've explored on the channel here: youtube.com/playlist?list=PLEwYhelKHmig6ttzH0nRL3OOQsGLtVrtX The animated model is from the "Mecanim Warrior Anim Free" package on the asset store - this effect should work on any object that you can apply the material to though. assetstore.unity.com/packages/p/mecanim-warrior-anim-free-6127 Join the World of Zero Discord Server: discord.gg/hU5Kq2uWhat Happens When You Snap Vertices To A Grid?World of Zero2021-02-10 | In this video I get to play with madness. We'll be exploring what happens if you try to "pixelate" a 3D mesh using a vertex shader. Everything in my mind is telling me this won't work and will create a *ton* of issues, but there's only one way to find out. Lets explore this idea together and use it to dive into vertex shaders in Unity 3D and some of their uses.
The general idea of this approach is to create a fixed size grid that we want to snap each of our vertices to. In order to accomplish this we can use a rounding trick I like to use. This trick involves expanding our objects by the grid size we're trying to accomplish, rounding the values, and then shrinking the values back down. For example if we have values between 0 and 1 (0, 0.25, 0.5, 0.75 for example) and we want to snap these values to a grid size of `0.1` we can divide the values by `0.1` (0, 2.5, 5, 7.5), round them (0, 3, 5, 8) and then multiply by `0.1` again (0, 0.3, 0.5, 0.8). This allows us to keep the same range of values while giving us control over the resolution of those values. We also use this technique in the [pixelated image effect](youtu.be/9bTFVaKGIIQ) from an earlier video on the channel.
When this grid snapping is applied against a mesh there are a few additional decisions we need to make. This includes what coordinate space we want to perform the operation in. Coordinate spaces describe an object relative to that space. For example an object space representation is an identical representation for each version of that object whereas a world space version of the same object would describe the unique position, rotation and scale of that object in the world. Which coordinate space we decide to create our grid in will effect the final result: if we snap vertices in object space then even as that object is rotated or moved through the world the rounded vertices will not change. However if we perform the grid snapping in world space the final results will change as the object is moved and rotated through the world. Depending on the effect we want to achieve different coordinate spaces may be more appropriate. For our testing purposes though we'll just use object space since this is the most straightforward to implement.
The vertex shader code that snaps to a grid looks like this (this is the surface shader implementation):
Note: the syntax is slightly different between the Surface Shader and Vertex Shader implementations however the principals are the same. Both implementations are demonstrated in the video.