Exercise 2 · Individual work

Objects: Creation, Deletion and Time

Drive a hero with the mouse or keyboard, fire eggs, and keep ten enemies in the world. Along the way: prefabs, collisions, and frame time vs. real time. Due date: see the course website.

Objective

Now that you're more comfortable with the Unity editor, let's create and destroy game objects at run time, detect collisions between them, and get a feel for the difference between frame time and wall-clock (real) time.

Individual workEach person must work on this exercise on their own.

Coverage

◆Prefabs

  • Create a prefab in the editor
  • Create (Instantiate) and delete (Destroy) objects at run time

↻Transform

  • Set position and rotation
  • Move along an object's own transform.up

⌨User interaction

  • World position from the mouse
  • Keyboard polling with the Input System
  • On-screen status text (TextMeshPro)

✦Concepts

  • The camera and the visible world bounds
  • Frame time vs. real time; rates per second
  • Collisions and responses; randomness
Start from the class examples Module 2 covers almost everything here: object navigation (2.1), prefabs (2.2), a Game Manager with UI text (2.3) and collisions with color changes (2.6).

What to build

Play my solution first. There are three kinds of objects: the hero, the eggs it fires, and the enemies. All speeds and rates below are per second, so multiply them by Time.smoothDeltaTime each frame (see EX1 if you need a refresher).

1

Camera and sprites

  • Main Camera: Orthographic, Size 100. The world spans y = −100 to +100.
  • The hero, eggs and enemies must each be a sprite made from an image (Texture Type: Sprite (2D and UI)). Built-in shapes and 3D objects don't count.
  • Sizes below are Transform Scale values, as in EX1. How big an object looks in world units also depends on its image's pixel size and Pixels Per Unit: my solution uses 128, so the 180-pixel hero at scale 5 is about 7 units wide.

Use any images you like, or the ones in my solution:

2

Hero

Transform Scale (5, 5, 1).

KeyBehavior
MToggles between mouse and keyboard control. Mouse mode is the default (it's easy for me to test).
Mouse modeThe hero's position follows the mouse at all times.
Keyboard modeThe hero moves along its own transform.up. Its initial speed is 20 units/second.
W / S heldKeyboard mode: speed increases / decreases gradually at 10 units/second² (i.e., by 10 units/second every second held). Keep the speed within [0, 100].
A / D heldTurns the hero left / right at 45°/second (in both modes).
Space heldFires one egg every 0.2 seconds (in both modes).
3

Eggs

  • Transform Scale (1, 1, 1), created from a prefab at the hero's position.
  • Aligned with the hero's transform.up at the moment it's fired, and then travels along its own transform.up at 40 units/second.
  • An egg is destroyed when it either leaves the world bounds or hits an enemy.
4

Enemies

  • Transform Scale (5, 5, 1), created from a prefab. They don't move in this exercise.
  • There are always exactly 10 enemies, each placed at a random position within the central 90% of the world bounds.
  • As soon as an enemy is destroyed, spawn a new one under the same rules.
When an enemy touches…Response
the heroThe enemy is destroyed.
an eggThe egg is destroyed and the enemy loses 20% of its current energy: multiply its alpha by 0.8. The 4th egg hit destroys the enemy.
Changing the alpha Color is a struct, so GetComponent<SpriteRenderer>().color.a *= 0.8f; doesn't compile. Copy the color, change the copy, and assign it back:
SpriteRenderer r = GetComponent<SpriteRenderer>();
Color c = r.color;
c.a *= 0.8f;
r.color = c;
5

Status text and quitting

Show the application status on screen with a UI Text (TextMeshPro) object, updated every frame. It must include:

  • Hero: control mode (Mouse/Keyboard), and the number of enemies the hero has touched
  • Egg: the number of eggs currently in the world
  • Enemy: the current enemy count (always 10), and the total number destroyed

For example:

HERO: Drive(Mouse)  TouchedEnemy(3)
EGG: OnScreen(12)
ENEMY: Count(10)  Destroyed(7)

Q quits the application. As in EX1, this only works in the built EXE.

The first time you add TextMeshPro text, Unity asks to import the TMP Essentials. Click Import (or use Window › TextMeshPro › Import TMP Essential Resources).

Hints

Mouse position in the world
using UnityEngine.InputSystem;

Vector3 p = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
p.z = 0f;
transform.localPosition = p;
Keys

Use Keyboard.current.wKey.isPressed for held keys and Keyboard.current.mKey.wasPressedThisFrame for toggles. Don't use Input.GetAxis(); it throws an exception in Unity 6 projects.

Rates per second
float dt = Time.smoothDeltaTime;
mSpeed += kAcceleration * dt;                        // W held: 10 units/second²
transform.Rotate(0f, 0f, kTurnRate * dt);           // A held: 45 degrees/second
transform.localPosition += mSpeed * dt * transform.up;
Firing every 0.2 seconds

Remember the time of the last shot (Time.time) and only fire again once 0.2 seconds have passed. Create the egg with Instantiate(eggPrefab, transform.position, transform.rotation) so it starts with the hero's orientation.

Collisions

Follow Module 2.6. For OnTriggerEnter2D to be called, give the hero and egg a Rigidbody2D (Body Type Kinematic) and a BoxCollider2D with Is Trigger checked, and give the enemy a BoxCollider2D with Is Trigger checked.

World bounds

The world is Camera.main.orthographicSize high on each side of the camera, and orthographicSize * Camera.main.aspect wide on each side.

Counting

A single Game Manager object (see Module 2.3) is a good place to keep the counts and spawn enemies. Eggs can report their creation and destruction to it from Start() and OnDestroy().

Stretch goal (optional, not graded)

  • Keep the hero inside the world bounds in keyboard mode.
  • Show the hero's current speed in the status text.

Submission

  1. A zip file named YourNameEX2.zip containing your entire project: every file in Assets, Packages and ProjectSettings, and nothing more.
  2. A separate folder with your PC EXE build. We'll double-click the EXE to run your project.
Using an AI assistant? That's fine, but you must understand and be able to explain every line you submit. At the top of your hero script, write a short comment (2–3 sentences, in your own words) explaining how keyboard mode changes the hero's speed, direction and position each frame.

Self-check before you submit

  • I unzipped my zip into a new, empty folder and opened it in Unity 6000.3.11f1. It opens and runs.
  • The zip has only Assets, Packages and ProjectSettings.
  • Double-clicking the EXE runs the game, and Q quits it.
  • The hero, eggs and enemies are sprites made from images.
  • Holding Space fires about 5 eggs per second.
  • The egg count in the status text goes back to 0 once all eggs have left the world or hit enemies.
  • Enemy count always shows 10; an enemy fades on each egg hit and disappears on the 4th.
  • In keyboard mode, holding S stops the hero (speed 0) rather than reversing it.
  • My hero script has the 2–3 sentence explanation comment at the top.

Credit distribution

ItemSub-itemCategory
Camera setting: Orthographic, Size 1005%
Scene setup: hero (scale 5), egg and enemy prefabs, all image sprites5%
Hero25%
M toggles mouse/keyboard control (mouse is the default)3%
Mouse mode: position follows the mouse4%
Keyboard mode: moves along transform.up, initial speed 20 units/second3%
Keyboard mode: W/S change speed gradually at 10 units/second², within [0, 100]5%
A/D turn at 45°/second5%
Space fires one egg every 0.2 seconds5%
Eggs15%
Scale 1, aligned with the hero's transform.up when fired5%
Travel along their transform.up at 40 units/second5%
Destroyed on leaving the world bounds (checked with the egg count)5%
Enemies25%
Always exactly 10 in the world5%
Spawned (and re-spawned) at random within 90% of the world bounds5%
Destroyed on touching the hero5%
Egg hit: egg destroyed, enemy alpha × 0.85%
Destroyed by the 4th egg hit5%
On-screen status text10%
Hero: control mode and number of enemies touched4%
Egg: number currently in the world3%
Enemy: current count and number destroyed3%
Q quits the application (in the EXE)5%
Proper submission10%
Zip unzips and runs in the editor, with only the four project folders5%
Separate EXE folder; double-click runs the game5%
Total100%
Remember to delete the other folders before zipping, especially Library. Unity regenerates it when the project opens.