Lerp Fundamentals in Unity

May 10, 2021

Lerp

Unity


Title:
How to Use Lerp (Unity Tutorial)

By:
Ketra Games


Youtube – Tutorial

Description:
A brief coverage of exactly how Lerp works in Unity with a couple ways to use it.


Overview

I was recently researching ways to effectively use Lerp in Unity and came across some strange implementations that made me unsure if I understood how it worked. This video however specifically covered that case and explained that it does work, but it’s not a particularly ideal solution.

The case covered is specifically called the “Incorrect Usage” in this video. It is when Time.deltaTime alone is entered as the time parameter for Lerp. As I thought, this is just entering some tiny number as a time parameter each time it is called, which is then used to just some value between the intial and final values entered into the Lerp. It is not very controlled, and it leads to a strange situation where it keeps getting called and updated but it does not theoretically reach the final position ever (although this may be different with how computers handle the values eventually).

Finally they cover a couple time parameters to use with Lerp to get a few varied results. SmoothStep is one they suggest to get a result similar to the “Incorrect Usage” but done properly. It adds a bit of a slowing effect as the value gets closer to the final result. They also show using an Animation Curve to control the value in many various mathematical ways over time.

via Blogger http://stevelilleyschool.blogspot.com/2021/05/lerp-fundamentals-in-unity.html

Game Project: Flying Game – Part 2 – 3D UI Guide with Rotational Matrices

May 4, 2021

Flying Game

UI & Matrix Rotations


Overview

I wanted to make a 3D UI element which could direct the player in open flying space towards a point of interest or goal. This needed to point towards the object positionally, as well as account for the rotation or direction the player is facing. This makes sure that no matter where they are and what direction they are facing, it can guide them to turn the proper direction and make informed decisions to move directly towards that goal.

After deciding that changing my frame of reference could be a solution for this problem, I found Unity’s InverseTransformDirection method which can change a Vector from one space to another. To make sure this was providing a result similar to what I expected mathematically, I also wrote out the math for performing a matrix rotation on the vector and was happy to see it gave the same results.

3D UI Element – Real Time Guide Towards Goal

Add a 3D Element to the Unity Canvas

You change the render mode of the Canvas to Screen Space – Camera, which requires adding a Camera reference. To satisfy this, create another Camera separate from the main with the above settings. Drag this Camera in as the reference for your Canvas. Now 3D objects can be added to the Canvas.

Make sure the 3D elements added are on the UI layer. Sometimes the scaling can be strange, so you may need to scale the objects up substantially to see them on the Canvas. Also your main Camera may separately render the object as well, so to avoid this remove the UI layer from the Culling Mask for your main Camera.

    Canvas Settings:

  • Render Mode = Screen Space – Camera
  • Render Camera = Created UI Camera
    UI Camera Settings:

  • Clear Flags = Depth only
  • Culling Mask = UI
  • Projection = Orthographic

Unity’s InverseTransformDirection to Set Guide Upward Ray

Using Unity’s “InverseTransformDirection()” method from the player’s transform with the vector pointing from the player’s position to the intended goal allowed me to change the frame of reference of the goal vector from world space to that of the player. This properly rotates the vector to associate itself with the player’s current rotation as well as their position relative to the goal.

Creating my Own Rotational Transformation on the Goal Vector to Compare to Unity’s InverseTransformDirection

To double check what this was doing, I found the math to change the frame of reference of a vector from one frame to another at the link attached. Since the player currently only rotates on a single axis (the y-axis in this case), I could directly copy the example seen in the video which investigates representing a vector in a new frame with a rotation about a single axis (to keep the terms simpler for now). Following this math I got the exact same results as Unity’s InverseTransformDirection method, indicating they perform the same operations.

Creates Vector from Player to Goal

private Vector3 PointTowardsGoal()
{
	return goal.position - player.transform.position;
}

Transforms Goal Vector from World Space to Player’s Space with Unity InverseTransformDirection

private Vector3 PointTowardsGoalRelativeToForward()
{
	// Translate direction to player's local space
	relativeDirectionFromForwardToGoal = player.transform.InverseTransformDirection(PointTowardsGoal());

	return relativeDirectionFromForwardToGoal;
}

Transforms Goal Vector from World Space to Player’s Space with Rotation Matrix Math

private Vector3 GoalVectorInFrameOfPlayer()
{
	// pr
	Vector3 originalVector = PointTowardsGoal();

	// Obtain rotation value (in radians); Rotation angle about the y-axis
	float theta = player.transform.localRotation.eulerAngles.y * Mathf.PI / 180;

	// p1
	Vector3 vectorInNewFrame = new Vector3(
		originalVector.x * Mathf.Cos(theta) - originalVector.z * Mathf.Sin(theta),
		originalVector.y,
		originalVector.x * Mathf.Sin(theta) + originalVector.z * Mathf.Cos(theta)
		);
		
	return vectorInNewFrame;
}



Flying Game Project: 3D UI Guide Towards Goal Prototype from Steve Lilley on Vimeo.

Video 1: Prototype of 3D UI Guide Using Unity InverseTransformDirection




Flying Game Project: Comparing Unity's InverseTransformDirection to my Own Rotational Matrices from Steve Lilley on Vimeo.

Video 2: Update Using Rotational Matrix Math on Goal Vector

Summary

It is good to know that for standard procedures where I want to change the relative frame of a vector that Unity’s InverseTransformDirection() method appears to do that. As showcased here, that can be a very strong tool when you need to translate vector information from your game’s world space to an element in your UI, whether that be through the player’s current frame reference or something else.

Learning how to setup a Canvas to use 3D assets in your UI is also good to know just to increase the flexibility of options you have when creating a UI. Some information can be difficult to convey with a 2D tool, so having that option can open avenues of clarity.

via Blogger http://stevelilleyschool.blogspot.com/2021/05/game-project-flying-game-part-2-3d-ui.html

Game Project: Flying Game – Part 1 – Introductory Movement and Camera Controller

April 30, 2021

Flying Game

Game Project


Overview

I wanted to do some work on a small, simple 3D game in Unity I could make within a week or so. My original focus is on player movement, and from there I decided to hone in on a flying game of some kind. I have been watching Thabeast721 on Twitch and he recently played Super Man 64 which I have also seen at Games Done Quick (GDQ) events and thought building off of and improving their flying controller could be a fun project.

Player Controllers

Controller #1 – Rotate Forward Axis

My initial thoughts on a basic flying player controller was to have left/right rotate the player on the y-axis, up/down rotate the player on the x-axis, and a separate button to propel the player in their current forward direction.

As a controller standard, I also tend to have the player’s input be received in the Update method to receive as often as possible, but then output these inputs as movement in FixedUpdate to keep it consistent on machines with different frame rates.

	private void Update()
    {
        horizontalInput = Input.GetAxisRaw("Horizontal");
        verticalInput = Input.GetAxisRaw("Vertical");

        if (Input.GetButton("Jump"))
        {
            isMoving = true;
        }
        else
        {
            isMoving = false;
        }
    }

    private void FixedUpdate()
    {
        // Inputs in reverse position for direction vector because that influences which axis that input rotates AROUND
        Vector3 direction = Vector3.Normalize(new Vector3(verticalInput * inversion, horizontalInput, 0.0f));
        Flying(direction);
    }

    private void Flying(Vector3 dir)
    {
        RotatePlayer(dir);
        MovePlayer(dir);
    }

    private void RotatePlayer(Vector3 dir)
    {
		transform.Rotate(dir * rotationSpeed * Time.deltaTime);
    }

    private void MovePlayer(Vector3 dir)
    {
		if (isMoving)
		{
			transform.position += transform.forward * movementSpeed * Time.deltaTime;
		}
    }

Controller #2 – Rotate on Y-Axis but Translate Directly Vertically

With my second approach I wanted to try and emulate the flying controller from Super Man 64 just to see how it felt. It seems like a more acarde-y style of flying with easier controls, so I thought it would be a good option to investigate. For this horizontal rotation (rotation on the y-axis) remained the same, as this is pretty standard with grounded player controllers as well.

The up and down rotation (rotation on the x-axis) however, was completely removed. The up/down inputs from the player simply influence the movement vector of the player, adding some amount of up or down movement to the player. This makes it much easier to keep the player’s forward vector relatively parallel to the ground and is much less disorienting than free-form rotational movement in the air.

	private void Start()
    {
        if (isInvertedControls)
        {
            inversion = -1.0f;
        }
    }

    private void Update()
    {
        horizontalInput = Input.GetAxisRaw("Horizontal");
        verticalInput = Input.GetAxisRaw("Vertical");

        if (Input.GetButton("Jump"))
        {
            isMoving = true;
        }
        else
        {
            isMoving = false;
        }
    }

    private void FixedUpdate()
    {
        // Inputs in reverse position for direction vector because that influences which axis that input rotates AROUND
        Vector3 direction = Vector3.Normalize(new Vector3(verticalInput * inversion, horizontalInput, 0.0f));
        Flying(direction);
    }

    private void Flying(Vector3 dir)
    {
        RotatePlayer(dir);
        MovePlayer(dir);
    }

    private void RotatePlayer(Vector3 dir)
    {
		transform.Rotate(dir.y * Vector3.up * rotationSpeed * Time.deltaTime);     
    }

    private void MovePlayer(Vector3 dir)
    {      
		if (isMoving)
		{
			Vector3 movementDirection = Vector3.Normalize(transform.forward + dir.x * Vector3.up);
			transform.position += movementDirection * movementSpeed * Time.deltaTime;
		}     
    }

Camera Controller

Follow Position

To follow the player’s position, I am using a really simple case where it just follows them at some fixed offset. The offset is originally determined by the initial position of the camera relative to the player, and then for the rest of its run its position is just that of the player summed with the offset.

Where transform.position is the position of the camera object:



offset = transform.position – player.transform.position;



transform.position = player.transform.position + offset;

Rotate to Follow

My first test just to initialize the camera follow was to child it to the player to see how it looked that way. This worked ok for following position, but having multiple rotation influences made this impossible to use quickly at first. As I changed the player controller to a more general, arcade-style, it worked better but was still poor for rotation.

To fix this I put the camera as a child onto a separate empty gameobject. This gameobject could then follow the player and rotate to rotate the camera around the player while keeping it at a fixed offset distance. This also made determining the rotation angle/looking vector from the camera to the player much simpler. Since the camera is rotate downward some, its forward vector is not in-line with the world z-axis anymore. This camera container however could keep its axes algined with the world’s axes. This meant I could just make sure to align this container’s forward vector with the player’s forward facing vector on the xz-plane. To do so it just required the following:

private void RotateView()
{
	Vector3 lookDirection = new Vector3(player.transform.forward.x, 0.0f, player.transform.forward.z);

	transform.rotation = Quaternion.LookRotation(lookDirection, Vector3.up);
}

Unity’s Quaternion.LookRotation method allows me to set the rotation of the object based on the direction of a forward facing vector (lookDirection in this case), with a perpendicular upward vector to make sure I keep the rotation solely around the y-axis.

The following is a quick look at how the final player controller and camera controller interact from this initial prototype approach:

Flying Game Project: Initial Player Controller and Camera Controller Prototypes from Steve Lilley on Vimeo.

Summary

via Blogger http://stevelilleyschool.blogspot.com/2021/04/game-project-flying-game-part-1.html

Observer Pattern in Unity with C# – by Jason Weimann

April 22, 2021

Observer Pattern

Game Dev Patterns


Title:
Observer Pattern – Game Programming Patterns in Unity & C#

By:
Jason Weimann


Youtube – Tutorial

Description:
Introduction to the observer pattern and implementing it in Unity through C#.


Overview

This tutorial covers the basics of the observer pattern in game development with two ways of implementing it in Unity. The first approach is relatively simple just to establish the concept, whereas the second approach uses events with C# to create a more flexible system.

Observer Pattern Basics

An object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes (usually by calling one of their methods)

Example Uses in Games:

UI elements updating when data behind them changes

Achievement systems

Implementation #1: Inheriting Observer and Subject Classes

Observer Class:

Abstract class your observers will inherit from

OnNotify() method that accepts a value and notification type


Subject Class:

Abstract class your subjects will inherit from

Hold information on their list of observers they report to

RegisterObserver() method to add Observers to list of those reporting to

Notify() passes a value and notification type on to all the observers they report to in their list, in turn calling their OnNotify methods with the passed on data

This example gets the point across, but is not particularly well suited for Unity or C# projects. Requires a base class on all observers and subjects (although could possibly be changed to using an interface system).

Implementation #2: Using Events

Subject objects create a ‘static event Action‘, which they then call when the requirements are met.

Observer objects have their own methods to perform when those same requirements are met, and they are connected by having the observers subscribe their relevant methods to that same ‘static event’.

This reduces the direct coupling between the observers and subjects, as well as any other objects involved. Should profile this as calling events every frame can start to lead to performance loss. As always, also need to be careful to properly unsubscribe methods from events when needed (such as when deactivating or destroying objects).

via Blogger http://stevelilleyschool.blogspot.com/2021/04/observer-pattern-in-unity-with-c-by.html

Architecture AI Pathing Project: Cleaning Build UI

March 15, 2021

Working with UI

Architecture AI Project


Working with UI

Since UI looked organized into 4 major groups vertically, I used a Vertical Layout Group for the overall control. I then filled this with 4 empty UI objects, one for each major UI group.

Vertical Layout Group

  • Anchor Preset: stretch/left (anchors to the left, but expands for full vertical screen space)
  • Pivot: (0, 0.5) (Moves pivot point to the far left, so width controls how much it expands out from edge, and Pos X can just remain 0)
  • Child Force Expand: Width (Helps expand everything to fit the full width)
  • Child Force Expand: Height (May not be needed)
  • Control Child Size: Width (May not be needed)
  • Padding: Left, Top, Bottom (Keep everything slightly away from edge)

Controlling the anchors and pivot is extremely important. After setting up the vertical layout group, a lot of the individual control is necessary for the horizontal organization. The anchors, the x position in particular, can be used to help stretch the UI objects to fit whatever is dictated by the overall layout group container.

Using Anchors

For example, many objects are side by side and want to fit half of the given width. To do this, the left object uses anchor X values of min = 0.0 and max = 0.5. The right object uses X values of min = 0.5 and max = 1.0. The values are percentage based, so this allocates the first half of the given space to the first object and the second half to the other.

Using Pivots

The pivot then ties in as this is the base point, or handle of the UI object, so this is the point that all the positioning is relative to. So many of the objects start with a pivot at (0.5, 0.5), which is in the center of the object. This requires annoying extra positioning values, normally half of the width of the object, to fit properly. By moving the pivots though, they become much easier to position.

Again, looking at the UI examples that have 2 objects split the space horizontally, the pivots are used somewhat similarly to the anchors. The left object has its pivot set to (0, 0.5), so the X is set to 0.0. The right object has its pivot set to (1.0, 0.5), so the X is set to 1.0. These are again percentage based, so the (0, 0.5) pivot moves the handle to the extreme left of the object, and the (1.0, 0.5) moves the pivot to the extreme right. This way, the “X position” (now named Left and Right) can just be set to 0. This is conjunction with the edited anchor points will position the object perfectly to fill half the space horizontally.

These uses of UI anchor and pivots can be seen in the following figure in the bottom two groups of UI elements as I worked through applying them (the section with the “Run Sim” button and the section with the “Output .csv” button). The upper sections had not been modified yet.


Fig. 1: Example of These UI Modifications in During Work in Progress (Only Lower 2 Sections)

Summary

I learned a lot about the workings of UI elements in Unity by getting this setup much more organized. The anchors help locate the extents of the positions of a UI element, where as the pivot is simply the base point all the positioning and scaling originates. I also found that changing the anchor presets just has a set value for this different options (which completely makes sense once you look at it). For instance, stretch just sets the anchors to 0.0 and 1.0 to force it to fit the area it is parented by (or the entire screen).

via Blogger http://stevelilleyschool.blogspot.com/2021/03/architecture-ai-pathing-project.html

Architecture AI Pathing Project: Fixing Weird Build Bugs

March 11, 2021

Build Issues

Architecture AI Project


Overview

After working on the project with a focus on using it in Editor for a while, we finally decided to try and see if we could build the project and work with it from there. Initially it did not provide anything useable. It would build, but nothing could be done. After a while, I isolated that the colliders were giving trouble so I manually added them for a time and that helped set up the base node grid. The file reader however was unable to provide data to the node grid, so only one aspect of applying data to the pathing node grid worked.

These issues made the build fairly unuseable, but provided some aspects to approach modifying in order to fix the build. After some work focusing on the issue with applying colliders and reading/writing files, I was able to get the builds into a decently workable spot with hope to get the full project useable in a build soon!

Unable to Apply Colliders with Script: Working with Mesh Colliders at Run Time

This first issue right off the start of opening the build was that my script for applying mesh colliders to all aspects of the model of interest was not working. This made sense as a cause for the node grid not existing as raycasts need something to hit to send data to the node grid. Further testing with simply dropping a ball in the builds showed it passed right through, clearly indicating no colliders were added.

I used a band aid fix temporarily by manually adding all the colliders before building just to see how much this fixed. This allowed the basic node grids to work properly again (the walkable and influence based checks). The daylighting (data from the file reader) was not working still however, which showed another issue, but it was a step in the right direction.

Solution

With some digging, I found that imported meshes in Unity have a “Read/Write Enabled” check that appears to initially be set to false on import. While this does not seem to have an effect when working in the editor, even in the game scene, this does seem to apply in a build. So without this checked, the meshes apparently lose some editing capabilities at run time, which prevented the colliders from being added by script. Upon checking this, adding the colliders worked as intended.

File Reader Not Working: Differences Between Reading and Writing Text Files in Unity, and the Difficulties of Writing

While this got the build up and working at least, we were still missing a lot of options with the node grid not being able to read in data from the File Reader. Initially I thought that maybe the files being read were just non-existent or packaged incorrectly so I checked that first. I was loading the files in through Unity’s Resources.Load() with the files in the Resources folder, so I thought they were safe, but I still needed to check. To do so I just added a displayed UI text that read out the name of the file loaded if found, and read out an error if not found. This continuously provided the name of the file, indicating it was being found and that may not be the problem.

Difference Between “Build” and “Build and Run” in Unity

I was doing all my testing by building the project, and then finding the .exe and running it myself. Eventually I tried “Build and Run” just to test a bit faster, and to my surprised, the project totally worked! The File Reader was now working as intended and the extra pathing type was being read in properly and applied to the underlying node grid! But this was not a true solution.

To double check, I closed the application and tried to open it again directly from the .exe. Once I did, I found that again, the project was NOT applying the data properly and the file reader was NOT working as intended. This is important to note as “Build and Run” may give false positives for your builds working, when they actually don’t when run properly.

I found an attempt at an explanation here when looking for what caused this, as I hoped it would also help me find a solution:



Unity Forums – Differences between Build – Build&Run?


One user suggests some assets read from the Assets folder within Unity’s editor may still be in memory when doing “Build and Run”, which is not the case when simply doing a build. Further research would be needed though to clarify what causes this issue.

Solution

This did not directly lead me to my solution, but it did get me looking at Unity’s development builds and the player.log to try and find what issues were being created during the running of the build. This showed me that one part of the system was having trouble writing out my debug logs that were still carrying over into the build.

Since these were not important when running the build, I just tested commenting them out. This actually fixed the process and the File Reader was able to progress as expected! This read the file in at run time, and applied the extra architectural data to the pathing node grid as intended!

Reading vs. Writing Files through Unity

This showed me some differences in reading and writing files through Unity, and how writing requires a bit more work in many cases. Unity’s build in Resources.Load() works plenty fine as a quick and dirty way to read files in, even in the building process as I have seen. Writing out files however requires much more finesses, especially if you are doing something with direct path names.

Writing out files pretty much requires .NET methods as opposed to built in Unity methods, and as such might not work as quickly and cleanly as you hope without some work. When done improperly, as I had setup initially, it directly causes errors and stops in your application when you finally build it as the references will be different from when they were running in the Unity editor. This is something I will need to explore more as we do have another aspect of the project that does need to write out files.

Summary

If you want to modify meshes in your builds and you run into issues, just make sure to check if the mesh has “Read/Write Enabled” checked. Reading files with Unity works consistently when using a Resources.Load() approach, but writing out files is much trickier. Finally, use the dev build and player.log file when building a project to help with debugging at that stage.

via Blogger http://stevelilleyschool.blogspot.com/2021/03/architecture-ai-pathing-project-fixing.html

Unity – Exploring the Physics – Rigidbody and Drag

March 10, 2021

Rigid Body Physics

Unity



Title: How is Drag Calculated by Unity Engine?




Unity Forum – Link



Description:
Explanation of someone’s testing of Unity’s rigid body drag value.


Overview

I was just exploring Unity’s physics through Rigidbodys and Physics Materials to see what different feels and effects I could get with them, and decided to delve a bit further into them.

Rigid Body

I was just doing very general testing without much research this time around just to see what I got from using the different values. Mass acts pretty much how you would expect, as it requires more force to accelerate the object and stops it faster when friction is involved.

Drag

Drag and Angular Drag however were a bit trickier. While Drag did reduce the acceleration of the object as it moved, and eventually the velocity as force stopped being applied, it did not appear to matter what direction or shape the object’s facing direction created. I tested it with a narrow box, and moving straight on the narrow side and moving completely perpendicular with the long face of the box resulted in the same max speed values.

While I assumed this meant the shape did not matter whatsoever, I tested a capsule and a box with the exact same settings in the Rigidbody component on the exact same surface with the same physics material, and the box gave a lower terminal velocity than the capsule. I could not find any reason for this, other than possibly different collider types may have different effects on how drag or friction impacts them.

The link I attached above is a bit old now, but it comes from someone that belives they found an accurate approximation of Unity’s drag. At the very least, several sources I came across indicated that drag is linearly related to velocity in Unity’s Phys X engine, which is different from true drag which related to the square of the velocity of an object. I would have to do more testing to see if this person’s formula is accurate now (since this is about 5/6 years old now), and will have to do some more research to see if I can find any more up to date takes on Unity’s drag.

Physics Materials

I have not delved into these far yet, but the basics seem to make sense. I have only been exploring the friction values, and they seem to act as expected. The dynamic friction slows down objects rubbing against a surface as they move, and the static friction presents a force that needs to be overcome before the objects starts to move. Bounciness and the combining of the factors are aspects I have not yet tested at all currently.


Fig. 1: Quick Snap Shot of My Unity Physics Testing Table

Summary

With my quick initial tests, some interesting results have already come up. As noted previously, the primitives seem to be effected by physics differently somewhere in the pipeline. I suspect it is the drag factor, but it could also be friction, or some other inherent factor. Another interesting note is that both boxes had the exact same max speeds, even though one made much more contact with the ground. I would like to perform some more testing to see if the friction values at least make it accelerate slower overall, and reach max speed slower.

via Blogger http://stevelilleyschool.blogspot.com/2021/03/unity-exploring-physics-rigidbody-and.html

Drawing and Rendering Many Cube Meshes in Unity

March 02, 2021

Drawing and Rendering Meshes

Unity


Title:
Drawing 1 Million cubes!


Unity – Forum

Description:
Discussions and code for drawing and rendering many cube meshes.


Overview

I wanted to be able to replicate the drawcube Gizmos in Unity I am using to portray data for my architecture project in the game scene and eventually builds of the project. To do this I need a very lightweight way to draw many small cube meshes, so I looked into drawing/rendering my own meshes and shaders. This option I came across in a Unity forum to just draw and render meshes on Update seemed decent enough so I investigated a simpler version for my needs.

Implementation

I could get away with a much simpler version of the CubeDrawer script found in the forum comments. I could strip out the batching and the randomization as I need very specific cubes and no where near the million cubes they were rendering. I am normally looking at somewhere in the thousands to ten-thousands, and want very specific locations.

So I stripped this script down and tweaked it some for my needs so I could feed the position and color data I was already creating from my node grids and heatmaps into this simpler CubeDrawer. I then had it build and render the cubes. It was able to give me the visual results I wanted, but I was seeing a significant performance reduction. The AI agents had stuttery movement and the camera control had a bit of lag to it. I’ll need to investigate ways to reduce the performance hit this has, but it’s a step in the right direction.

via Blogger http://stevelilleyschool.blogspot.com/2021/03/drawing-and-rendering-many-cube-meshes.html

Architecture AI Pathing Project: Rename Dropdown Elements

February 16, 2021

Dropdown and Input Field UI

Architecture AI Project


Renaming Items in Spawn/Target Dropdown Lists

To get the spawn/target object lists into the dropdowns quickly and accurately, I had them simply add their gameobject names to the dropdowns for the individual item names. These objects however tend to have very long names as they are constructed from several elements coming from the Revit system to accurately identify them. While useful, they are too wordy for identification purposes here and can actually make them harder to find and keep track of. Because of this, we wanted to investigate a way to rename the elements in the list to make them easier to identify in the future.

To accomplish this I looked to add a UI Input Field where any name could be entered and this could be used to rename current items in the dropdown lists. Since there are two dropdowns (Spawn list and Target list), I added two different buttons to account for these. One button applies the current Input Field string as the name of the currently selected Spawn dropdown item, the other button applies it to the Target dropdown item.

The following images help show the name changer in action. The crucical elements are located in the top/central left.

Fig. 1: Initial Setup with Newly Included Input Field and Name Changing Buttons


Fig. 2: Effect of Adding Text to Input Field and Selecting the ‘Rename Spawn’ Button

Clean Up and Error Reduction

Restricting Controls when Accessing Input Field

I added some camera controls to help get around the environment, which included some keyboard shortcuts. These shortcuts however would activate while typing within the Input Field initially. I wanted to disable the camera controller while in the Input Field, so I found Unity has an easy way to determine if a UI element is currently focused, which can be used as a bool to dictate controls. This check can be done with the following:



EventSystem.current.currentSelectedGameObject


So I added a check that if this is null, allow the camera controller inputs, otherwise, disable them.

Null Input Field Check and Instant Dropdown Item Refresh

To keep the dropdown from getting too confusing and adding weird blank items, I added a check to make sure the Input Field is not null or empty before allowing the buttons to edit the current dropdown names. I also found initially that the dropdown item name would change in the dropdown, but it would not be reflected in the current dropdown selections. This looke awkward as I am always updating the current selection, so it would not actually be reflected until you selected the item from the dropdown again. To fix this, Unity’s dropdowns have their own method called RefreshShownValue(), which perfectly resolved this situation.

via Blogger http://stevelilleyschool.blogspot.com/2021/02/architecture-ai-pathing-project-rename.html

Unity Twin Stick Shooter Tutorial by Turbo Makes Games

February 3, 2021

Gamepad Joystick Inputs

Unity

Title:
How to Make a Twin Stick Shooter in Just 4 Hours – Unity Beginner Tutorial

By:
Turbo Makes Games


Youtube – Tutorial

Description:
Full tutorial on making a simple twin stick shooter in Unity.


Introduction

I was mostly looking for the basics of setting up twin stick shooter input controls in Unity, mainly with how to setup the second stick, and came across this full tutorial for twin stick shooters. I can use the player controller and input setup information to cover that for sure, and having access to the rest of the tutorial can be useful for ideas and concepts if I want to help flesh out my example.

Twin Stick Controls for Gamepad in Unity

To setup the right joystick for a gamepad in a project such as a twin stick shooter in Unity, you go to the “Project Settings” and go to the “Input” section. Here you can modify the list of inputs Unity is dealing with, so you can add the extra joystick. The easiest way to do this quickly for another stick is simply duplicating the default “Horizontal” and “Vertical” options and renaming them. Once renamed, just change their axis to 4th axis (for the x-axis of your right stick) and 5th axis (for the y-axis of your right stick). This should provide you the additional input options for the right stick of a gamepad.

via Blogger http://stevelilleyschool.blogspot.com/2021/02/unity-twin-stick-shooter-tutorial-by.html