Video Game Design and Coding · PLECK lesson

PLECK lesson 132 · suggested week 27, day 2

Bound enemy and update costs

Objective. Prevent runaway creation and unnecessary per-frame work.

Godot Engine Standard desktop editor 4.7.2-stable, GDScript (Godot 4), Compatibility renderer. Headless Godot 4.7.2.stable.official.ed1daf0bf passed 106 assertions on the supplied scaffolds, including malformed JSON saves. Audio used the Dummy driver and a synthetic WAV, not a speaker. The visual editor, browser export, and signed-in submission were not tested. The desk still does not run a student's own upload.

About 55 minutes. The due date is chosen by a parent.

Constraints, bounded systems, seed testing and an AI assessment

Suggested pace: Recall and predict 5 min; Read instruction and scaffold 12 min; Build or design the assigned artifact 25 min; Run acceptance tests 8 min; Explain and checkpoint 5 min.

Materials: Godot Standard 4.7.2 desktop editor (GDScript, Compatibility renderer), Local course folder and prior checkpoint, No paid assets or public account required.

Comes after VGC-L131.

Performance starts with sensible limits. Use a fixed small guard count, avoid spawning in _process, and cache stable references with @onready or exported fields. Do not search the entire scene tree every frame for a player that already has a reference. Measure before claiming an optimization helped. For this small project record object counts and use Godot’s monitors while running the same seed. Optimize the actual repeated operation, not a harmless line chosen because it looks complicated.

Worked example

A procedural bug report might say seed 17, build alpha2, start at entrance, move right, expected clear corridor, actual blocking wall. The seed makes reproduction practical. Scaffold C-TIMER — Timer-based spawning with a hard cap Setup: World Node2D root contains Node2D Hazards and Timer SpawnTimer: wait_time 1.2, autostart On, one_shot Off. Hazard scene root Area2D has a CircleShape2D radius 12 and C-HAZARD. Attach script to World and drag Hazard.tscn into hazard_scene Inspector field. Set viewport 640x360. Name Hazards group not needed. This script is a separate lab; merge its _ready into an existing manager rather than declaring a second _ready. ```gdscript extends Node2D @export var hazard_scene: PackedScene @export var spawn_limit: int = 12 func _ready() -> void: $SpawnTimer.timeout.connect(_spawn) func _spawn() -> void: if hazard_scene == null or $Hazards.get_child_count() >= spawn_limit: return var hazard := hazard_scene.instantiate() as Area2D $Hazards.add_child(hazard) hazard.position = Vector2(randf_range(20.0, 620.0), -20.0) ``` Scaffold C-GUARD-AI — A readable patrol/chase/return state machine Setup: Create CharacterBody2D Guard with visible circle or polygon and matching collider. Layer 4 mask 2 for walls. Attach script and assign target to your Player instance in Inspector. Level is one open rectangle; this is steering, not navigation around walls. Damage remains a separate sensor/manager event. Draw detection radii on a design diagram before tuning values. ```gdscript extends CharacterBody2D enum Mode { PATROL, CHASE, RETURN } @export var target: Node2D @export var speed: float = 70.0 var mode: Mode = Mode.PATROL var home: Vector2 var patrol_target: Vector2 func _ready() -> void: home = global_position patrol_target = home + Vector2(80, 0) func _physics_process(delta: float) -> void: if not is_instance_valid(target): velocity = Vector2.ZERO return var distance: float = global_position.distance_to(target.global_position) if mode != Mode.CHASE and distance < 120.0: mode = Mode.CHASE elif mode == Mode.CHASE and distance > 180.0: mode = Mode.RETURN var destination: Vector2 if mode == Mode.CHASE: destination = target.global_position elif mode == Mode.RETURN: destination = home if global_position.distance_to(home) <= maxf(3.0, speed * delta): mode = Mode.PATROL else: destination = patrol_target if global_position.distance_to(patrol_target) <= maxf(3.0, speed * delta): patrol_target = home if patrol_target != home else home + Vector2(80, 0) var offset := destination - global_position velocity = offset.normalized() * minf(speed, offset.length() / maxf(delta, 0.001)) move_and_slide() ```

Timer-based spawning with a hard cap

GDScript (Godot 4, not Scratch, Python, JavaScript or C#). Scaffold C-TIMER. Copy starts from this text. The desk does not run it.

Scene and node setup

World Node2D root contains Node2D Hazards and Timer SpawnTimer: wait_time 1.2, autostart On, one_shot Off. Hazard scene root Area2D has a CircleShape2D radius 12 and C-HAZARD. Attach script to World and drag Hazard.tscn into hazard_scene Inspector field. Set viewport 640x360. Name Hazards group not needed. This script is a separate lab; merge its _ready into an existing manager rather than declaring a second _ready.

extends Node2D
@export var hazard_scene: PackedScene
@export var spawn_limit: int = 12
func _ready() -> void:
    $SpawnTimer.timeout.connect(_spawn)
func _spawn() -> void:
    if hazard_scene == null or $Hazards.get_child_count() >= spawn_limit:
        return
    var hazard := hazard_scene.instantiate() as Area2D
    $Hazards.add_child(hazard)
    hazard.position = Vector2(randf_range(20.0, 620.0), -20.0)

Checks to run in the editor

Native Godot 4.7.2.stable.official.ed1daf0bf headless compile and representative node-tree/runtime tests passed; see native-qa-results.json. Visual UI, audible output, exports and website submission still need separate checks.

A readable patrol/chase/return state machine

GDScript (Godot 4, not Scratch, Python, JavaScript or C#). Scaffold C-GUARD-AI. Copy starts from this text. The desk does not run it.

Scene and node setup

Create CharacterBody2D Guard with visible circle or polygon and matching collider. Layer 4 mask 2 for walls. Attach script and assign target to your Player instance in Inspector. Level is one open rectangle; this is steering, not navigation around walls. Damage remains a separate sensor/manager event. Draw detection radii on a design diagram before tuning values.

extends CharacterBody2D
enum Mode { PATROL, CHASE, RETURN }
@export var target: Node2D
@export var speed: float = 70.0
var mode: Mode = Mode.PATROL
var home: Vector2
var patrol_target: Vector2
func _ready() -> void:
    home = global_position
    patrol_target = home + Vector2(80, 0)
func _physics_process(delta: float) -> void:
    if not is_instance_valid(target):
        velocity = Vector2.ZERO
        return
    var distance: float = global_position.distance_to(target.global_position)
    if mode != Mode.CHASE and distance < 120.0:
        mode = Mode.CHASE
    elif mode == Mode.CHASE and distance > 180.0:
        mode = Mode.RETURN
    var destination: Vector2
    if mode == Mode.CHASE:
        destination = target.global_position
    elif mode == Mode.RETURN:
        destination = home
        if global_position.distance_to(home) <= maxf(3.0, speed * delta):
            mode = Mode.PATROL
    else:
        destination = patrol_target
        if global_position.distance_to(patrol_target) <= maxf(3.0, speed * delta):
            patrol_target = home if patrol_target != home else home + Vector2(80, 0)
    var offset := destination - global_position
    velocity = offset.normalized() * minf(speed, offset.length() / maxf(delta, 0.001))
    move_and_slide()

Checks to run in the editor

Native Godot 4.7.2.stable.official.ed1daf0bf headless compile and representative node-tree/runtime tests passed; see native-qa-results.json. Visual UI, audible output, exports and website submission still need separate checks.

Bound enemy and update costs — evidence task

  1. 1. Set explicit caps for guards and generated walls.
  2. 2. Record object/node counts during a two-minute run and identify one avoidable repeated lookup.

Deliverable. Performance bounds table and before/after observation.

Acceptance checks

Understanding question. Why is a lower line count not proof of faster code?

Include a downloadable project ZIP with project.godot, .tscn, .gd and original asset files when code changes. A private, teacher-accessible download link to that ZIP is equivalent. Screenshots or a playthrough do not replace editable source.

If this is still shaky. Keep guard patrol in a reserved open lane and the player route guaranteed. Avoid adding maze pathfinding to this project. Start with the first assigned task and re-run its acceptance test before adding the remaining feature.

Optional extra. Add one optional guard route only if the generator can prove its lane remains clear. Document one changed parameter, your prediction, and the observed effect; optional, not required for completion.

Name ____________________ Date ____________________