Skip to content

Custom NpcActivities

PXAV edited this page Feb 14, 2021 · 1 revision

NPC activities are a great way to extend the functionality of NPCs. They can make use of NPC ticks.

Creating an activity class

Every activity has to extend from NpcActivity<T>, which provides some default methods. In the generic clause, provide your class name. This ensures that the parent activity class knows which type to return in the default builder methods. By default, you don't have to implement any method of the parent class. Only take the methods you need and override them.

public class TestActivity extends NpcActivity<TestActivity> {
  
}

NPC ticks

KelpNpcs have their own tick system, which is slightly slower than Minecraft's tick system. This saves performance but is still fast enough to make animations look smooth and fluently.

  • The normal Minecraft tick system has up to 20 ticks per second, which is a tick interval of about 50ms.
  • NPC ticks have half the speed of normal ticks with 10 ticks per second or 100ms between each tick.

All tick operations of NPCs are executed asynchronously by default, so make sure to only use thread-safe operations or ServerMainThread class.

Basic control methods

You can override methods such as onTick, which is called on every NPC tick. This example shows how an activity might look like:

public class TestActivity extends NpcActivity<TestActivity> {

  private int executions = 0;

  // it is recommended to add a static factory method
  public static TestActivity create() {
    return new TestActivity();
  }

  @Override
  public void onStart(KelpNpc kelpNpc) {
    System.out.println("Activity has started.");
    System.out.println("It is called for the first time. This method is only called");
    System.out.println("once during the activity's lifetime.");
  }

  @Override
  public void onTick(KelpNpc kelpNpc) {
    // toggle the npc custom name state
    kelpNpc.customNameShown(!kelpNpc.isCustomNameShown());
    executions++;

    // if the name has been toggled 200 times,
    // cancel the activity.
    if (executions == 200) {
      finish();
    }

  }

  @Override
  public void onRemove(KelpNpc kelpNpc) {
    System.out.println("This is called when the npc is removed and the activity");
    System.out.println("has to be stopped/interrupted.");
  }

}

Finishing activities

If your activity is finishable (such as a walking activity), you can call the finish() method. This will remove the activity from the NPC and it won't be called anymore.

You can listen for activities to finish by calling onFinish when you add the activity to the NPC:

npc.addActivity(TestActivity.create()
  .onFinish(() -> {
    System.out.println("Test activity has finished");
  }));

Removing activities

You can remove activities from an NPC at any time using the following method:

npc.removeActivity(TestActivity.class);
Clone this wiki locally