Skip to content

03.Creating the enemy

la.panon. edited this page Apr 17, 2025 · 2 revisions

The tutorial corresponding to this page is here. Please proceed to the "Enemy script".

Let me show you the whole code first.

# nim/nimmain/src/classes/gdmob.nim
import gdext
import gdext/classes/gdAnimatedSprite2D
import gdext/classes/gdSpriteFrames
import gdext/classes/gdSceneTree

type Mob* {.gdsync.} = ptr object of RigidBody2D

method ready(self: Mob) {.gdsync.} =
  let AnimatedSprite2D = self/"AnimatedSprite2D" as AnimatedSprite2D
  let VisibleOnScreenNotifier2D = self/"VisibleOnScreenNotifier2D" as VisibleOnScreenNotifier2D

  discard VisibleOnScreenNotifier2D.connect("screen_exited", self.callable"_on_visible_on_screen_notifier_2d_screen_exited")

  let mobTypes = newArray AnimatedSprite2D.spriteFrames[].getAnimationNames
  AnimatedSprite2D.play(mobTypes.pickRandom.get(StringName))

proc on_VisibleOnScreenNotifier2D_screen_exited(self: Mob) {.gdsync, name: "_on_visible_on_screen_notifier_2d_screen_exited".} =
  queueFree self

The one that should be explained in this context is AnimatedSprite2D.spriteFrames[]. What is this []?

spriteFrames() returns SpriteFrames, a subclass of type Resource. gdext-nim uses our gdref type instead of Nim's ref to emulate Godot's reference counting mechanism.

The spriteFrames() is precisely that it returns gdref SpriteFrames.

Because of implementation constraints, we need to call the [] operator to get the raw object out of the gdref-wrapped Resource.

# nim/nimmain/bootstrap.nim
  import gdext
  import classes/gdPlayer
+ import classes/gdMob


  GDExtensionEntryPoint

Don't forget to build and replace the Mob node.

« Previous: Coding the player

Next: The main game scene »

Clone this wiki locally