Zigging and Zagging the enemies.

Today we will create a zig-zag movement on our enemies to increase the difficulty of the game a little.

We will start by opening our ‘Enemy’ script and adding some new variables. We will create two private floats, one named ‘_frequency’ that is set to 3f, and the second named ‘_magnitude’ set to 2f. These variables will dictate the intensity and how often the zig turns to zags. Next, we will add a pair of ‘Vector3’ variables called ‘_position’ and ‘_axis’.

In ‘Start’ we will set our ‘_position’ to transform.position. We will set ‘_axis’ to transform.right.

Let’s create a new function called ‘DiagonalMovement’. This is for later on when we want some enemies to move in a straight line down and some to move in a diagonal.

In this function, we will add ‘_position’ with ‘Vector3.down’ then multiply ‘Time.deltaTime’ and multiply all that by ‘_enemyMovementSpeed’. We will then set our ‘transform.position’ equal to ‘_position’ plus our ‘_axis’ then multiply that by ‘Mathf.Sin’. The parameters of Sin will be Time.time multiplied by our ‘_frequency’, then we will multiply the whole thing by ‘_magnitude’. The Mathf.Sin is what will cause the zig zags to happen. When the frequency variable is met, the enemy will be told to move the opposite way.

After that, we will write an if statement that will reset the enemy at the top of the screen if it reaches the bottom of the screen. It’s exactly the same as the if statement in ‘CalculateMovement’, with one addition. We will add ‘_position’ is equal to ‘transform.position’.

That’s all for the code. Let’s just comment out our ‘CalculateMovement’ function in ‘Update’ for now, until we get different enemy types created. Let’s now put our ‘DiagonalMovement’ function in ‘Update’ for now to test things out.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Chipping Away at a Monolith

Data Structures and Algorithms

Firebase App Development: Things To Know

Want To Improve Your Productivity? Use A Text Analysis API

Check Tin Prices In Canadian Dollars From LME

Don’t Worry, President Trump Knows He’s Lost

30 Days Coding Challenge — Day 19

Why object-oriented programming is a bad programming paradigm.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chance Cornell

Chance Cornell

More from Medium

Making a Dash Mechanic for your game

Tesseract — Teleportation in Virtual Reality

texture material with the correct dimensions

Rhythm Quest Devlog 21 — Level Graphics Revamp

Forgotton Shrine — 3D Project Breakdown