World of Zero
A Static Glowing Ring - Ripple Shader - Part 1
updated
***
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
Trie.Net is available on [GitHub](github.com/gmamaladze/trienet) and [Nuget](nuget.org/packages/TrieNet/). You can find more documentation and learn about it's other features here: github.com/gmamaladze/trienet
If you want to learn more about how Trie's work as a data structure you can learn more about that on Wikipedia: en.wikipedia.org/wiki/Trie
If you're interested in how to build a `Trie` from scratch we've done that in an earlier video you can find here: youtube.com/watch?v=4nmVXKu6e_Q
For more information about the Mermaid diagrams I use at the start of this video, check out [my video on Mermaid JS](youtube.com/watch?v=7_2IroEs6Is). Recently support for these diagrams was even [added to GitHub](docs.github.com/get-started/writing-on-github/working-with-advanced-formatting/creating-diagrams).
***
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
* `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.
The JSON.NET documentation is available here: newtonsoft.com/json/help/html/Introduction.htm
***
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
Creating [`ScriptableObject`'s allows you to configure Mono Behavior's using pre-configured data](docs.unity3d.com/Manual/class-ScriptableObject.html)
You can use the `CreateAssetMenuAttribute` to [create asset menus and more easily create new `ScriptableObject`'s](docs.unity3d.com/ScriptReference/CreateAssetMenuAttribute.html).
---
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
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.
For more information you can check out the documentation here: docs.unity3d.com/ScriptReference/AssetPostprocessor.OnPostprocessAllAssets.html
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/hU5Kq2u
This stream is also available on the Microsoft Developer and Microsoft Reactor Channels:
Microsoft Developer: twitch.tv/microsoftdeveloper
Microsoft Reactor: @MicrosoftReactor
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
This stream is also available on the Microsoft Developer and Microsoft Reactor Channels:
Microsoft Developer: twitch.tv/microsoftdeveloper
Microsoft Reactor: @MicrosoftReactor
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
This stream is also available on the Microsoft Developer and Microsoft Reactor Channels:
Microsoft Developer: twitch.tv/microsoftdeveloper
Microsoft Reactor: @MicrosoftReactor
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
This stream is also available on the Microsoft Developer and Microsoft Reactor Channels:
Microsoft Developer: twitch.tv/microsoftdeveloper
Microsoft Reactor: @MicrosoftReactor
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
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:
```csharp
Task.Run(async () =˃ {
int progressId = Progress.Start("My Task");
await Task.Delay(5000);
Progress.Finish(progressId);
});
```
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
You can find more information about the Unity Progress API here: docs.unity3d.com/ScriptReference/Progress.html
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
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");
```
You can get a copy of Inkscape here: inkscape.org
The Inkscape Wiki has more information about how you can get started using the Inkscape CLI: wiki.inkscape.org/wiki/index.php/Using_the_Command_Line
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/hU5Kq2u
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
Get OpenSCAD: openscad.org/index.html
OpenSCAD's documentation: openscad.org/documentation.html
OpenSCAD on GitHub: github.com/openscad/openscad
You can get a copy of my models and the SCAD files that generate them here: github.com/runewake2/scad-examples
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
The module we created for a basic dice looks like this:
```OpenSCAD
module CreateDice(size = 16) {
textSize = size * 0.75;
textLocation = size / 2 - 1;
textExtrusionSize = 2;
difference() {
cube([size, size, size], center = true);
translate([0,0,textLocation]) linear_extrude(textExtrusionSize) text("1", size=textSize, halign="center", valign="center");
rotate([180, 0, 0]) translate([0,0,textLocation]) linear_extrude(textExtrusionSize) text("6", size=textSize, halign="center", valign="center");
rotate([0, 90, 0]) translate([0,0,textLocation]) linear_extrude(textExtrusionSize) text("2", size=textSize, halign="center", valign="center");
rotate([0, 270, 0]) translate([0,0,textLocation]) linear_extrude(textExtrusionSize) text("5", size=textSize, halign="center", valign="center");
rotate([90, 0, 0]) translate([0,0,textLocation]) linear_extrude(textExtrusionSize) text("3", size=textSize, halign="center", valign="center");
rotate([270, 0, 0]) translate([0,0,textLocation]) linear_extrude(textExtrusionSize) text("4", size=textSize, halign="center", valign="center");
}
}
```
Get OpenSCAD: openscad.org/index.html
OpenSCAD's documentation: openscad.org/documentation.html
OpenSCAD on GitHub: github.com/openscad/openscad
You can get a copy of my models and the SCAD files that generate them here: github.com/runewake2/scad-examples
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
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:
* `pre-commit`
* `prepare-commit-msg`
* `commit-msg`
* `post-commit`
* `pre-push`
* `applypatch-msg`
* `pre-applypatch`
* `post-applypatch`
* `pre-rebase`
* `post-checkout`
* `post-merge`
* `post-update`
* `pre-auto-gc`
* `post-rewrite`
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:
```json
"files.exclude": {
"**/.git": false
},
```
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/hU5Kq2u
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:
* **[Transient](learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicecollectionserviceextensions.addtransient)**: A new copy of your service will be constructed every time it is requested by an object.
* **[Scoped](learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicecollectionserviceextensions.addscoped)**: Your service will be instantiated once for the entire execution scope - usually covering a single web request. Every reference to the service within that scope will share the same copy of the service.
* **[Singleton](learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.servicecollectionserviceextensions.addsingleton)**: Your service will be instantiated once - the first time it is requested - and then that instance will be reused everywhere else it is needed for the entire time your application is running.
You can learn more about using .NET's Dependency Injection features at these links:
* http://aka.ms/usingdotnetdependencyinjection
* learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection
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/hU5Kq2u
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:
```csharp
var bounds = collider.bounds;
cameraFrustum = GeometryUtility.CalculateFrustumPlanes(camera);
if (GeometryUtility.TestPlanesAABB(cameraFrustum, bounds))
{
renderer.sharedMaterial.color = Color.green;
}
else
{
renderer.sharedMaterial.color = Color.red;
}
```
You can learn more about dot product here: youtu.be/8cZo-c-f1yc
***
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
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.
You can find more information about using Global Usings as part of the using directive documentation here: learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive#global-modifier
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
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
This videos thumbnail uses a globe SVG from here: commons.wikimedia.org/wiki/File:Emojione_BW_1F30E.svg
You can turn on Implicit Usings in your .NET 6 projects by adding this line to your Project file.
```csproj
˂ImplicitUsings˃enable˂/ImplicitUsings˃
```
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`.
You can find a more in-depth dive into this feature here: dotnetcoretutorials.com/2021/08/31/implicit-using-statements-in-net-6
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
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.
***
* You can learn more about Project Jupyter here: jupyter.org
* You can find more information about working with Jupyter Notebooks in VS Code here: code.visualstudio.com/docs/datascience/jupyter-notebooks
* The Jupyter extension for Visual Studio Code is available here: marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter
* .NET Interactive is open source on GitHub here: github.com/dotnet/interactive
***
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
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!
***
The GitHub Bookmark Generator project is available publicly on GitHub here: github.com/runewake2/GitHubBookmarks
The GitHub GraphQL API Explorer is here: docs.github.com/en/graphql/overview/explorer. You can use this to explore and run test queries against GitHub's API.
***
If your interested in some of my other Cloud based videos I stream at twitch.tv/MicrosoftDeveloper regularly and some of my other videos can be found on the Microsoft Reactor YouTube channel: youtube.com/c/MicrosoftReactor1
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/hU5Kq2u
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;
static void Main(string[] args)
{
Console.WriteLine($"Class: {nameof(Program)}"); //Class: Program
Console.WriteLine($"Variable: {nameof(aVariableNamedFoo)}"); //Variable: aVariableNamedFoo
Console.WriteLine($"Property: {nameof(Foo)}"); //Property: Foo
Console.WriteLine($"Function: {nameof(Main)}"); //Function: Main
}
}
```
`nameof` can also be used against members of other objects. For example the `nameof` a List's Count can be retrieved using:
```csharp
var contents = new List˂Page˃();
Console.WriteLine($"List Count: {nameof(contents.Count)}"); //List Count: Count
```
You can learn more about using `nameof` in the C# documentation here: docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/nameof
***
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
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!
1. [Building Real-Time Web Apps with SignalR](youtube.com/watch?v=k5rdhYj6TB8)
2. [Connecting a Web App to SignalR](youtube.com/watch?v=c0zmYjQ8KWA)
3. [Creating a Real-Time Web Canvas](youtube.com/watch?v=hgq1CYEJg_Q)
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/hU5Kq2u
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!
1. [Building Real-Time Web Apps with SignalR](youtube.com/watch?v=k5rdhYj6TB8)
2. [Connecting a Web App to SignalR](youtube.com/watch?v=c0zmYjQ8KWA)
3. [Creating a Real-Time Web Canvas](youtube.com/watch?v=hgq1CYEJg_Q)
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/hU5Kq2u
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!
1. [Building Real-Time Web Apps with SignalR](youtube.com/watch?v=k5rdhYj6TB8)
2. [Connecting a Web App to SignalR](youtube.com/watch?v=c0zmYjQ8KWA)
3. [Creating a Real-Time Web Canvas](youtube.com/watch?v=hgq1CYEJg_Q)
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/hU5Kq2u
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
Want to learn more about .NET MAUI? You can find the docs here: dotnet.microsoft.com/en-us/apps/maui
.NET MAUI is Open Source! You can check it out on GitHub here: github.com/dotnet/maui
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/hU5Kq2u
`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.
You can find more information about `SphereCast`'s in Unity's documentation here: docs.unity3d.com/ScriptReference/Physics.SphereCast.html
***
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);
}
}
```
Looking for an introduction to `Raycast`s? Check out my video on Raycasting in Unity: worldofzero.com/videos/detecting-objects-with-raycasts-in-unity3d
If your interested in some of my other Cloud based videos I stream at twitch.tv/MicrosoftDeveloper regularly and some of my other videos can be found on the Microsoft Reactor YouTube channel: youtube.com/c/MicrosoftReactor1
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/hU5Kq2u
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:
```hlsl
Texture2D shaderTexture;
SamplerState samplerState;
float4 main(float4 pos : SV_POSITION, float2 tex : TEXCOORD) : SV_TARGET {
return shaderTexture.Sample(samplerState, tex);
}
```
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:
```hlsl
float4 main(float4 pos : SV_POSITION, float2 tex : TEXCOORD) : SV_TARGET {
float4 color = shaderTexture.Sample(samplerState, tex);
return float4(color.r, 0, 0, color.a) ;
}
```
Some additional documentation on Windows Terminal pixel shaders is available on the Windows Terminal GitHub page here: github.com/microsoft/terminal/blob/main/samples/PixelShaders/README.md
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:
```json
"actions":
[
...
{
"command": "toggleShaderEffects",
"keys": "shift+f10"
}
]
```
In my example pressing the Shift and F10 key would toggle shader effects.
***
If you don't have the Windows Terminal you can download it here: microsoft.com/en-us/p/windows-terminal/9n0dx20hk701
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/hU5Kq2u
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!
```json
"profiles":
{
...
"list":
{
{},
{},
// Insert your profile here!
}
}
```
***
You can download the Windows Terminal for your machine here: microsoft.com/en-us/p/windows-terminal/9n0dx20hk701
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
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:
{{˂ shader id="NsjGRG" ˃}}
You can see an example of this flag applied to the Windows Terminal (with full source code) here: worldofzero.com/posts/pride-windows-terminal
I've explored step and smoothstep in more depth in this video: youtu.be/-vGNd8pnbYs
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
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/hU5Kq2u
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.
Browse the `UnityEditor.AnimatedValues` API:
- [`AnimBool`](docs.unity3d.com/ScriptReference/AnimatedValues.AnimBool.html)
- [`AnimFloat`](docs.unity3d.com/ScriptReference/AnimatedValues.AnimFloat.html)
- [`AnimQuaternion`](docs.unity3d.com/ScriptReference/AnimatedValues.AnimQuaternion.html)
- [`AnimVector3`](docs.unity3d.com/ScriptReference/AnimatedValues.AnimVector3.html)
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
***
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/hU5Kq2u
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/hU5Kq2u
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.
### The Code
```csharp
// C# Calculator Tree - by World of Zero
// Learn more: worldofzero.com/v/V2KwrmjNIrY
using System;
// create tree to represent:
// 2 * (3 + 5)
//
// *
// / \
// 2 +
// / \
// 3 5
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/hU5Kq2u
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/hU5Kq2u
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;
}
```
***
Learn more about using `yield` with more examples in this video: youtube.com/watch?v=bsZjfuTrPSA
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
***
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.
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;
void UseMathClass() {
Essentials.Math.CalculateAngleOfImpact(...);
Sys.Math.Cos(...);
}
```
***
I've uploaded other projects on my website at worldofzero.com
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
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.
You can see my video on using Unity's Async Scene Loading features [here](worldofzero.com/videos/learning-async-unity-scene-loading/).
{{% youtube id="Oq2ytDvHTYM" %}}
***
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/hU5Kq2u
Thanks to [Jason Storey](youtube.com/channel/UCG6MguMC0ntGCvVyaEwTPzw) for recommending the use of `ContextMenu`'s. You can find more of their content as a guest in videos at Infallible Code: youtube.com/user/charlesamat
### Code Examples
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/hU5Kq2u
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
var sceneStatus = SceneManager.LoadSceneAsync("SceneName", LoadSceneMode.Additive);
sceneStatus.completed += (e) =˃ Debug.Log("Scene Loaded");
```
or by using a Unity Coroutine:
```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:
```csharp
SceneManager.LoadScene("SceneName", LoadSceneMode.Additive);
```
***
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/hU5Kq2u
To cut a 5 minute long clip out of a larger video named `original-video.mp4` we'd run a command like:
```sh
ffmpeg -i original-video.mp4 -ss 00:05:00 -to 00:10:00 -c copy edited-video.mp4
```
* `-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/hU5Kq2u
If present a geometry shader occurs after an a vertex shader but before the fragment shader following one of these two paths:
```mermaid
graph LR;
vert([Vertex Shader])
geom([Geometry Shader])
frag([Fragment Shader])
vert-- v2g --˃geom
geom-- g2f --˃frag
vert-- v2f --˃frag
```
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):
```shader
[maxvertexcount(3)]
void geom(triangle v2g IN[3], inout TriangleStream˂g2f˃ triStream)
{
float3 lightPosition = _WorldSpaceLightPos0;
float3 v0 = IN[0].pos.xyz;
float3 v1 = IN[1].pos.xyz;
float3 v2 = IN[2].pos.xyz;
float3 normal = normalize(cross(v0 - v1, v1 - v2));
float lightStrength = (dot(lightPosition, normal) + 1) / 2;
g2f OUT;
OUT.norm = normal;
OUT.lightStrength = lightStrength;
OUT.pos = mul(UNITY_MATRIX_VP, IN[0].pos);
triStream.Append(OUT);
OUT.pos = mul(UNITY_MATRIX_VP, IN[1].pos);
triStream.Append(OUT);
OUT.pos = mul(UNITY_MATRIX_VP, IN[2].pos);
triStream.Append(OUT);
}
```
***
My intro to exploring Geometry Shaders: youtu.be/HY6qFbmbij8
My video covering implementing diffuse lighting in more detail: youtu.be/4XfXOEDzBx4
A collection of other visual effects we've built: youtube.com/watch?v=l_2uGpjBMl4&list=PLEwYhelKHmig6ttzH0nRL3OOQsGLtVrtX
Watch the entire series where we explore this concept of snapping vertices to a grid: youtube.com/watch?v=e8NItqF_9hQ&list=PLEwYhelKHmiixWR3Tn5dYt1iUlSCL6OFq
Join the World of Zero Discord Server: discord.gg/hU5Kq2u
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.
```diff
void vert(inout appdata_full v) {
+ v.vertex = mul(unity_ObjectToWorld, v.vertex);
v.vertex /= _GridSize;
v.vertex = round(v.vertex);
v.vertex *= _GridSize;
+ v.vertex = mul(unity_WorldToObject, v.vertex);
}
```
You can view the entire playlist of implementing this effect here: youtube.com/playlist?list=PLEwYhelKHmiixWR3Tn5dYt1iUlSCL6OFq
***
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/hU5Kq2u
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):
```shader
void vert(inout appdata_full v) {
v.vertex /= _GridSize;
v.vertex = round(v.vertex);
v.vertex *= _GridSize;
}
```
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.
You can view the entire playlist of implementing this effect here: youtube.com/playlist?list=PLEwYhelKHmiixWR3Tn5dYt1iUlSCL6OFq
***
More Visual Effects we've built on World of Zero: youtube.com/playlist?list=PLEwYhelKHmig6ttzH0nRL3OOQsGLtVrtX
Unity's Surface Shader examples: docs.unity3d.com/Manual/SL-SurfaceShaderExamples.html
If you're interested in learning more about coordinate spaces (object space/world space/etc) this article goes into a bit more depth and also describes the relationships between the different coordinate spaces: http://davidlively.com/programming/graphics/coordinate-spaces
The Bomber Bug asset is located here: assetstore.unity.com/packages/p/bomber-bug-pack-pbr-63127
Come chat in the World of Zero Discord Server: discord.gg/hU5Kq2u


