Unity Dev: Dinosaur Laser Fight

Alex Somerville
3 min readMar 21, 2021
Sorry, no actual dinosaurs… yet.

Got a couple things to showcase in this one. In previous articles we covered how to control the movement of our Player object and how to spawn our “Lasers”. That’s all well and good, but games need limitations and rules to be really engaging. On top of this, lasers need to laser, and right now they’re just sittin’ around being lazy lasers.

Objective 1: Make the lasers go zoom!
Objective 2: Confine the Player movement to the first half of the playable area.
Objective 3: Let the Player warp from the top of the screen to the bottom, and vice versa.

Lasers go Zoom!

Pretty simple task in theory. We want the lasers to travel from their spawn point in a straight line to the right.

First step is creating a C# Script called “Laser”. This then gets applied to our Laser prefab so that all instantiated instances of the prefab are controlled in the same way by it.

Telling the laser to travel to the right is as simple as using Translate in the scripts Update() . I’ve added mine to it’s own void CalculateMovement() which I then call inside of Update()

We then Destroy() the instance of the laser once it’s off screen so that we don’t have a billion little laser babies flying off into the unknown forever.

Movement Limits

Here we’re going to make it so that the Player can’t move further than, say, the first half of the playable area.

First, figure out what the constraint values are going to be. You can use the inspector on the Player object and drag it around to check. In my case, the maximum x is going to be 0 (horizontally center) and the minimum is going to be -9f (almost right at the back of the playable area).

In our Player script, we already have the code to move our object around the screen so we just need to add a one liner as seen below. We use Mathf.Clamp() to let our transform.position constrain the x value between -9f and 0f.

Warp Time!

When our Player goes off the screen at the bottom, we want them to come back in from the top, and vice versa. In this case, we can simply add in some logic that’s going to check for these situations and then immediately change the Player position when they’re true. Since we’re dealing with logic, let’s first write out some pseudo-code to help us understand what we’re attempting.

This makes sense and seems like it’ll accomplish what we’re looking for. Turning that into actual code is pretty straight forward from here.

Pretty much the same thing. When we place the Player to the opposite side of the screen, we also place them at their current x position so that, even though they’re being moved vertically, they stay in the same spot horizontally when warping.

--

--

Alex Somerville

On a quest to become a game developer. Still sometimes providing unsolicited advice about how to function in society.