Enemy Creation Part 1: Introduction to Unity Physics

Joe
3 min readMay 6, 2021

--

To create the enemy start with a prototype. I chose a cube and just to be a bit different I rotated it 45 degrees along the z axis, which means that some of the vector math needed to be adjusted.

The enemy itself needs to go from the top of the screen to the bottom. Using the now familiar

Move a gameobject

Using just the Vector3.up multiplied by -1, speed and Time.deltatime does not yield the behavior that is wanted

Movement before fixing vector math

To fix this and and get the desired behavior the vector math needs to be corrected. As the cube has been rotated 45 degrees the line of travel to keep it straight would be along both the x axis and the y axis. Make a variable to store the modified vector movement

New Vector3 value for moving straight

This can now be applied to the movement code

Updated movement code

Now The cube will move straight from the top of the screen to the bottom

Enemy now moves in a straight line from top of screen to bottom

To provide a random starting location for the cube use the

Random.Range to randomize starting location of enemy

Ensuring the starting y value is above the gameplay area use the randomizing code for the x value. Now the enemy will randomize the starting location for entering the gameplay area. After the enemy leaves the screen at the bottom the enemy it can be re-used by changing the transform location back to the top and randomly assigning it another starting location.

Randomize enemy starting location

Now that the enemy is created, moving as desired, and entering the play area in a random starting location it is time to add some basic physics.

To have gameobjects interact with each other two items are required, a rigidbody component and a collider. The rigidbody component is only required for one of the two objects that collide. So for this we can add a rigidbody component to the laser, as it can collide with the enemy and a rigidbody component to the enemy, as it can collide with the player.

When adding a rigidbody component, if gravity is not needed it can be turned off. In this case, as all three gameobjects (Laser, Player, and Enemy) have their own movement script gravity is not required and can be turned off. Do this for both the enemy prefab and the laser prefab.

Adding the rigidbody component in Unity

This is the first step and if the collider is not modified at this point then there will be some interesting and undesired behavior.

Collider not modified

This will be continued in Enemy Creation Part 2.

--

--