Simple Object Movement in Unity
The last task to complete GameDevHQ’s 2D Game Design course requires that we create a large boss with all the bells and whistles at the end of a Space Shooter level.
As with many things in Unity, doing simple movement is not intuitive. For example, I sought to create a direction vector based upon the current position of an object that would direct the object to a specific target position.
For example, I wanted to move the object vertically 5 units and horizontally by 3 units. But this doesn’t work. The issue is that you cannot modify each individual axis in a vector. So, joining them together into a Vector3, I wrote this:
But this didn’t work, either. To solve this, I A) created a simple offset (-2 and 2 for this new example) and B) added it to come up with the target position. But then, C) I also had to .normalize the result for the direction to always work as you can see in this code here:
Then, when it came time to move the object toward the target position, I could include this single line of code in Update().
transform.Translate(direction * speed * Time.deltaTime);
It’s truly amazing how much power 4 lines of code can produce. But coming up with the right 4 lines is not always so easy.
To see the practical use of this code, this image shows how the enemy objects move out of the way when the player shoots at them.
Thanks to Jonathan and Al at GameDevHQ, our superhero team lead Dan and Economic Development Alliance of Hawaii for making this program available for those of us impacted by Covid-19.