Dynamic Runtime Animation

Problem:
Dynamic animations based upon the speed of movement.

Assets used:
Futuristic, floating basketball hoop, hung in air by thrusters

First the hoop rotates a certain angle to point its thrusters in the desired move direction. Before this rotation finishes, it starts moving.
Towards the end of the movement, it reverses rotation direction to point the thrusters in the opposite direction to simulate stopping force. This rotation should end before the hoop arrives at the final location.
Finally, when the hoop finishes the movement, it rotates back to the idle position.

Flowchart for reference:

Movement Flowchart
Movement Flowchart

Naturally, the hoop’s speed should start slow, gain speed as it moves, then slow down towards the end. The rotations should do the same, to simulate real world movement.

Each movement cycle needs a certain angle to rotate based upon desired speed, which is based upon move distance. If the hoop moves a very small amount, it only needs to rotate a small angle to accomplish this.

My initial thought was to use Unity’s Animation.SetCurve, but that got real messy real quick. It seemed like I was playing with something I shouldn’t. Also, the transform of the object cannot be moved if an animation is applied to the transform.

The alternative: Coroutines!

First the rotation animation. Since the only difference between the 3 rotations is the angle, I just need one method which takes the angle as a parameter:

This method will rotate the object within a specific time. If you look at the flowchart, you’ll see the object movement will start during the initial rotation. Therefore we need to implement a flag to tell a movement script to begin movement. This can simply be a bool which a movement script constantly checks to see if it’s true. We’ll call this startMoving. Another variable we need is a float that represents the time the startMoving bool should be turned on. This can be called startMovementPosition. Finally, we implement it by placing a if statement in the while statement:

Since each of these steps in the movement process are all associated with the same, singular, movement, it makes sense to be in a Finite State Machine. Explanation of this is beyond the scope of this post, but there are plenty of resources out there on the internet.
A state machine contains individual steps, which are represented by each box in the flowchart. In each step, an enter method is initially run once, then an execute method is run continuously, and finally an exit method is run when the state is changed:

For the first initial rotation:

Which is implemented like:

Now the Moving State:

And again, the HoopLateralMovementController:

The CheckReadyForReverseRotation method that the MovingState continuously checks is key for the animation to behave, and thus look correct. The timeRemaining is the time left in the object movement. The rotationTimeNeeded is the amount of time needed to perform the reverse rotation. Since the reverse rotation needs to finish before the movement finishes, the timeRemaining is multiplied by 0.9f, which is 90% of the time. Then, if the new timeRemaining is less than or equal to the rotation time needed, the reverse rotation is started. The rotation will then finish right before the movement finishes.

The ReverseRotate state:

And subsequent methods in HoopLateralMovementController:

In the HoopRotation script:

Like the startMoving flag set in the initial rotation, a similar flag called currentlyRotating in the movement coroutine is set to false, which signals the final rotation to trigger.

Getting the most out of your clouds!

So you got some cloud sprites and you figure you’ll just casually scroll them across the screen. Well, let me ask you one question:

Would Steve Jobs casually scroll clouds across the screen???

I rest my case. Here’s how to add some ‘je ne sais quoi’ to your boring scrolling clouds:

For starters, here are my clouds:
clouds

and my eye-popping background:

background

If you think about any object that moves, the further away it is, the slower it moves, and the fainter the object’s color. Surprisingly, the same is true for clouds. With this in mind, we can start by assigning a scroll speed to each cloud, then assign an alpha value to it’s sprite’s color, based upon the speed. I’ve experimented in the scene view in Unity, and I like an alpha range of 0.15 to 0.85, and a scroll speed range of 0.001 to 0.02.

Assigning the speed is easy:

Then, the alpha based upon the speed:

Great! So when to use these methods? Logically, when the cloud passes out of the cameras view. When this happens, the sprite needs to be reset at the other side of the screen, and then the methods run. Luckily, we have this beaut: MonoBehaviour.OnBecameInvisible()

At the moment the cloud fully scrolls offscreen, this baby is run, and we perform our logic. So simple!

Now, if these tweaks aren’t enough, just let your creativity fly and play with Unity’s abundant features. You could:

Flip it! (In the style of Queen)

or maybe…Size it!

or howbout…Color it!

This one was a little tricky. As you can see, I’m assigning the the same value to r, b, and g. This effectively adjusts the grayscale, which is what we want, because clouds are grayscale. You could definitely get a sunset effect going if you want, just play with the color in Unity’s editor.
Also, I experimented again in the scene view to find the 0.7 and 1.0 float values.

Simple star dust trail in Unity

Why make things difficult? Life doesn’t need to be difficult.

I started my project to create a beautiful comet-like trail, and had plans to spend a week or more on it. In the end, however, I realized a nice looking trail can be created simply by combining two Unity components, with a little nifty scripting:
Trail Renderer
Particle System

The trail will be used to show the shot path of a basketball, so I want it to show until a make or miss is definite. This is where the particle system comes in.

I first create a prefab to hold the particle system, trail renderer, and ball trail script.
For the particle system, I use a simple star texture for the material:
six-point-star

The initial setup:
Screen Shot 2016-03-29 at 2.20.11 PM

Next I randomize the size of the particles:

increase the emission rate, and base emission off distance, so the rate is constant no matter the speed of the ball:
Emission rate

Also emit using a shape:
emission_shape

We then fade the particles over time, using color over time option. In order to select the alpha channel, you must click the top tab/arrow:
color_over_time
opacity_over_time

Next, we change the particle color to white, and add these options:
size_over_time
velocity_over_time

For the trail, adjust the time depending on desired trail length, and make start width larger then end width. Then, adjust the colors to gradually decrease alpha in order to create a fade effect:
Screen Shot 2016-04-06 at 3.48.31 PM

Finally, to add some polish, we fade the trail out using the TrailRenderer options startWidth, endWidth, and time:

And BAM!


Quaternions

January 4 – Quaternion Fun Times

Background:
I’m building a character customization screen, where a user can mix and match different character parts, like arms, legs, etc. in order to create a custom, character.
Additionally, the entire character will be rotating at a set speed while the user chooses parts.
To properly connect new parts, we need to follow the following steps:

1. Connect the arm shoulder joint position to the torso shoulder joint position
2. Rotate the new arm to match the current body rotation
3. Rotate the new arm to match it’s elbow joint to the torso elbow joint

If we perform the first two steps, we get this:

Improper rotation

The second set of arms is set correctly to the torso shoulder joints, but its elbow joints aren’t properly lined up.
The current code is as follows:

We need to be careful here. The transform structure of the arm is:

arm_hiearchy

If we move the “left_upper_shoulder_joints” transform, we create an offset from it’s parent. We could use local rotation of the joint to work around this issue, but let’s instead keep everything together. We’ll figure the offset of the parent and child, then account for that when moving the parent:

Next we need to rotate each set of arms to match the direction of the torso.
First, we get both the rotation between the torso’s shoulder and elbow joints, and the rotation between the arm’s shoulder and elbow joints, then plug them into this nice little Unity function:

Quaternion.FromToRotation

unity_from_to_method

Our fromDirection is the current arm direction, and our toDirection is the current torso arm direction:


Hmm, it appears that the rotation is off until it gets back to its original instantiation position. This tells us that our code isn’t accounting for the current rotation

In order to add two rotations together, we must actually multiply them. Let’s do a basic assignment operator for multiplication:


Weird, it seems like its rotating in the opposite direction.

While researching quaternions, I remember seeing something about quaternions being “non-commutative”, which simply means:
x*y != y*x

With this in mind, let’s change the last line and test:


Woo! So, quaternion addition being non-commutative, this is correct:

And this is not:

To attempt to explain, adding two quaternions together (by multiplication) is synonymous to performing the first rotation, then the second, one after the other.

In other words, you’re taking the first quaternion rotation, and applying it to the second.

Since we want to rotate the arm itself, we need to apply our arm rotation to the current torso rotation.

The torso rotation (part.transform.rotation) is essentially a constant horizontal spin. If we apply the current torso rotation to our new arm rotation, we’re applying a horizontal spin to our new arm. Then applying the needed arm rotation on a different axis.

That’s how I understand it, but don’t quote me, I could be completely wrong!

Anyway, I hope this helps with quaternion troubles, and everyone can avoid the same hangups I had!