hytale-custom-entities

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Creating Custom Hytale Entities

创建Hytale自定义实体

Complete guide for defining custom entities with AI, components, spawning, and animations.
本指南详细介绍如何定义具备AI、组件、生成规则和动画的自定义实体。

When to use this skill

本技能的适用场景

Use this skill when:
  • Creating new entity types (mobs, NPCs, creatures)
  • Designing AI behaviors with sensors and actions
  • Setting up entity spawning rules
  • Adding custom entity components
  • Configuring entity animations and models
  • Creating interactive NPCs
在以下场景中使用本技能:
  • 创建新的实体类型(生物、NPC、怪物)
  • 设计带有传感器和动作的AI行为
  • 设置实体生成规则
  • 添加自定义实体组件
  • 配置实体动画与模型
  • 创建可交互NPC

Entity Architecture Overview

实体架构概述

Hytale uses an ECS (Entity Component System) architecture:
  • Entity: Container with unique ID
  • Components: Data attached to entities
  • Systems: Logic that processes components
Hytale采用ECS(Entity Component System,实体组件系统)架构:
  • Entity:容器,具有唯一ID
  • Components:附加到实体的数据
  • Systems:处理组件的逻辑

Entity Hierarchy

实体层级结构

Entity
├── LivingEntity (has health, inventory, stats)
│   ├── Player
│   └── NPCEntity (has AI role, pathfinding)
├── BlockEntity (block-attached entities)
├── ProjectileEntity
└── ItemEntity (dropped items)
Entity
├── LivingEntity (拥有生命值、背包、属性)
│   ├── Player
│   └── NPCEntity (拥有AI角色、寻路功能)
├── BlockEntity (依附于方块的实体)
├── ProjectileEntity
└── ItemEntity (掉落的物品)

Entity Asset Structure

实体资源结构

my-plugin/
└── assets/
    └── Server/
        └── Content/
            ├── Entities/
            │   └── my_creature.entity
            ├── Roles/
            │   └── my_creature_role.role
            └── Spawns/
                └── my_creature_spawn.spawn
my-plugin/
└── assets/
    └── Server/
        └── Content/
            ├── Entities/
            │   └── my_creature.entity
            ├── Roles/
            │   └── my_creature_role.role
            └── Spawns/
                └── my_creature_spawn.spawn

Basic Entity Definition

基础实体定义

File:
my_creature.entity
json
{
  "DisplayName": {
    "en-US": "Custom Creature"
  },
  "Model": "MyPlugin/Models/custom_creature",
  "Health": 20,
  "MovementSpeed": 1.0,
  "Role": "MyPlugin:CustomCreatureRole",
  "Tags": {
    "Type": ["Monster", "Hostile"]
  }
}
文件
my_creature.entity
json
{
  "DisplayName": {
    "en-US": "Custom Creature"
  },
  "Model": "MyPlugin/Models/custom_creature",
  "Health": 20,
  "MovementSpeed": 1.0,
  "Role": "MyPlugin:CustomCreatureRole",
  "Tags": {
    "Type": ["Monster", "Hostile"]
  }
}

Entity Properties Reference

实体属性参考

Core Properties

核心属性

PropertyTypeDescription
DisplayName
LocalizedStringEntity name
Model
StringModel asset reference
Health
FloatMaximum health
Role
StringAI role reference
Team
StringTeam/faction ID
Tags
ObjectClassification tags
属性类型描述
DisplayName
LocalizedString实体名称
Model
String模型资源引用
Health
Float最大生命值
Role
StringAI角色引用
Team
String队伍/阵营ID
Tags
Object分类标签

Physical Properties

物理属性

PropertyTypeDefaultDescription
MovementSpeed
Float1.0Base move speed
BoundingBox
ObjectautoCollision box
Mass
Float1.0Physics mass
Gravity
Float1.0Gravity multiplier
CanSwim
BooleanfalseCan swim in water
CanFly
BooleanfalseCan fly
StepHeight
Float0.5Max step-up height
属性类型默认值描述
MovementSpeed
Float1.0基础移动速度
BoundingBox
Objectauto碰撞箱
Mass
Float1.0物理质量
Gravity
Float1.0重力系数
CanSwim
Booleanfalse是否能在水中游泳
CanFly
Booleanfalse是否能飞行
StepHeight
Float0.5最大爬坡高度

Combat Properties

战斗属性

PropertyTypeDescription
AttackDamage
FloatBase attack damage
AttackSpeed
FloatAttacks per second
AttackRange
FloatMelee attack range
Armor
FloatDamage reduction
KnockbackResistance
FloatKnockback reduction
属性类型描述
AttackDamage
Float基础攻击力
AttackSpeed
Float每秒攻击次数
AttackRange
Float近战攻击范围
Armor
Float伤害减免值
KnockbackResistance
Float击退抗性

Visual Properties

视觉属性

PropertyTypeDescription
Scale
FloatModel scale
RenderDistance
FloatMax render distance
ShadowSize
FloatShadow radius
GlowColor
ColorOutline glow color
Particles
StringAmbient particles
属性类型描述
Scale
Float模型缩放比例
RenderDistance
Float最大渲染距离
ShadowSize
Float阴影半径
GlowColor
Color轮廓发光颜色
Particles
String环境粒子效果

AI Role System

AI角色系统

NPCs are controlled by Roles containing Instructions with:
  • Sensors: Conditions for activation
  • BodyMotion: Movement behavior
  • HeadMotion: Look behavior
  • Actions: Effects to execute
NPC由包含指令的**角色(Roles)**控制,指令包含:
  • Sensors(传感器):触发条件
  • BodyMotion(身体动作):移动行为
  • HeadMotion(头部动作):朝向行为
  • Actions(动作):执行的效果

Basic Role Definition

基础角色定义

File:
my_creature_role.role
json
{
  "MotionController": "Walk",
  "DefaultInstruction": {
    "Sensor": {
      "Type": "Always"
    },
    "BodyMotion": {
      "Type": "Wander",
      "Speed": 0.5,
      "Radius": 10
    },
    "HeadMotion": {
      "Type": "Nothing"
    }
  },
  "Instructions": [
    {
      "Priority": 10,
      "Sensor": {
        "Type": "SensorPlayer",
        "Range": 15,
        "Condition": "Visible"
      },
      "BodyMotion": {
        "Type": "Pursue",
        "Target": "Player",
        "Speed": 1.0
      },
      "HeadMotion": {
        "Type": "Watch",
        "Target": "Player"
      },
      "Actions": [
        {
          "Type": "Attack",
          "Range": 2.0,
          "Damage": 5,
          "Cooldown": 1.0
        }
      ]
    }
  ]
}
文件
my_creature_role.role
json
{
  "MotionController": "Walk",
  "DefaultInstruction": {
    "Sensor": {
      "Type": "Always"
    },
    "BodyMotion": {
      "Type": "Wander",
      "Speed": 0.5,
      "Radius": 10
    },
    "HeadMotion": {
      "Type": "Nothing"
    }
  },
  "Instructions": [
    {
      "Priority": 10,
      "Sensor": {
        "Type": "SensorPlayer",
        "Range": 15,
        "Condition": "Visible"
      },
      "BodyMotion": {
        "Type": "Pursue",
        "Target": "Player",
        "Speed": 1.0
      },
      "HeadMotion": {
        "Type": "Watch",
        "Target": "Player"
      },
      "Actions": [
        {
          "Type": "Attack",
          "Range": 2.0,
          "Damage": 5,
          "Cooldown": 1.0
        }
      ]
    }
  ]
}

Motion Controllers

动作控制器

ControllerDescription
Walk
Ground-based movement
Fly
Aerial movement
Dive
Swimming movement
Hover
Stationary flight
控制器描述
Walk
地面移动
Fly
空中移动
Dive
游泳移动
Hover
悬停飞行

Sensor Types

传感器类型

SensorDescriptionParameters
Always
Always true-
Never
Always false-
Random
Random chance
Chance
SensorPlayer
Detect players
Range
,
Condition
SensorEntity
Detect entities
Range
,
EntityType
,
Tags
SensorDamage
When damaged
Threshold
SensorHealth
Health check
Below
,
Above
SensorTime
Time of day
DayTime
,
NightTime
SensorNav
Navigation state
HasPath
,
AtDestination
SensorDistance
Distance check
Target
,
Min
,
Max
传感器描述参数
Always
始终触发-
Never
从不触发-
Random
随机触发
Chance
SensorPlayer
检测玩家
Range
,
Condition
SensorEntity
检测实体
Range
,
EntityType
,
Tags
SensorDamage
受到伤害时触发
Threshold
SensorHealth
生命值检测
Below
,
Above
SensorTime
昼夜时间检测
DayTime
,
NightTime
SensorNav
导航状态检测
HasPath
,
AtDestination
SensorDistance
距离检测
Target
,
Min
,
Max

Body Motion Types

身体动作类型

MotionDescriptionParameters
Wander
Random wandering
Speed
,
Radius
,
IdleTime
Pursue
Chase target
Target
,
Speed
,
StopDistance
Flee
Run from target
Target
,
Speed
,
SafeDistance
MoveTo
Go to position
Position
,
Speed
MoveAway
Move away
Target
,
Distance
Patrol
Follow path
Waypoints
,
Speed
Circle
Circle target
Target
,
Radius
,
Speed
Stay
Don't move-
TakeOff
Start flying-
Land
Stop flying-
Teleport
Instant move
Position
动作描述参数
Wander
随机游荡
Speed
,
Radius
,
IdleTime
Pursue
追逐目标
Target
,
Speed
,
StopDistance
Flee
逃离目标
Target
,
Speed
,
SafeDistance
MoveTo
移动到指定位置
Position
,
Speed
MoveAway
远离目标
Target
,
Distance
Patrol
沿路径巡逻
Waypoints
,
Speed
Circle
环绕目标
Target
,
Radius
,
Speed
Stay
保持静止-
TakeOff
开始飞行-
Land
停止飞行-
Teleport
瞬间移动
Position

Head Motion Types

头部动作类型

MotionDescriptionParameters
Watch
Look at target
Target
Aim
Aim at target
Target
,
Offset
Look
Look direction
Direction
Nothing
Don't control head-
动作描述参数
Watch
注视目标
Target
Aim
瞄准目标
Target
,
Offset
Look
朝向指定方向
Direction
Nothing
不控制头部-

Action Types

动作类型

ActionDescriptionParameters
Attack
Melee attack
Damage
,
Range
,
Cooldown
RangedAttack
Projectile attack
Projectile
,
Speed
,
Cooldown
ApplyEntityEffect
Apply effect
Effect
,
Duration
,
Target
PlaySound
Play sound
Sound
,
Volume
SpawnEntity
Spawn entity
Entity
,
Count
SetStat
Modify stat
Stat
,
Value
SetFlag
Set flag
Flag
,
Value
Notify
Trigger event
Event
,
Data
Wait
Delay
Duration
动作描述参数
Attack
近战攻击
Damage
,
Range
,
Cooldown
RangedAttack
远程攻击
Projectile
,
Speed
,
Cooldown
ApplyEntityEffect
施加效果
Effect
,
Duration
,
Target
PlaySound
播放音效
Sound
,
Volume
SpawnEntity
生成实体
Entity
,
Count
SetStat
修改属性
Stat
,
Value
SetFlag
设置标记
Flag
,
Value
Notify
触发事件
Event
,
Data
Wait
延迟执行
Duration

Complex AI Example

复杂AI示例

Aggressive mob with multiple behaviors:
json
{
  "MotionController": "Walk",
  "CombatRange": 2.0,
  "AggroRange": 20,
  "LeashRange": 40,
  
  "DefaultInstruction": {
    "Sensor": { "Type": "Always" },
    "BodyMotion": {
      "Type": "Wander",
      "Speed": 0.4,
      "Radius": 15,
      "IdleTime": { "Min": 2, "Max": 5 }
    },
    "HeadMotion": { "Type": "Nothing" }
  },
  
  "Instructions": [
    {
      "Name": "ReturnToLeash",
      "Priority": 100,
      "Sensor": {
        "Type": "SensorDistance",
        "Target": "LeashPosition",
        "Min": 40
      },
      "BodyMotion": {
        "Type": "MoveTo",
        "Target": "LeashPosition",
        "Speed": 1.5
      }
    },
    {
      "Name": "AttackPlayer",
      "Priority": 50,
      "Sensor": {
        "Type": "And",
        "Sensors": [
          {
            "Type": "SensorPlayer",
            "Range": 2.5,
            "Condition": "Visible"
          },
          {
            "Type": "SensorCooldown",
            "Cooldown": "AttackCooldown",
            "Ready": true
          }
        ]
      },
      "BodyMotion": { "Type": "Stay" },
      "HeadMotion": {
        "Type": "Aim",
        "Target": "Player"
      },
      "Actions": [
        {
          "Type": "Attack",
          "Damage": 8,
          "Animation": "attack_swing"
        },
        {
          "Type": "SetCooldown",
          "Cooldown": "AttackCooldown",
          "Duration": 1.5
        }
      ]
    },
    {
      "Name": "ChasePlayer",
      "Priority": 40,
      "Sensor": {
        "Type": "SensorPlayer",
        "Range": 20,
        "Condition": "Visible"
      },
      "BodyMotion": {
        "Type": "Pursue",
        "Target": "Player",
        "Speed": 1.0,
        "StopDistance": 1.5
      },
      "HeadMotion": {
        "Type": "Watch",
        "Target": "Player"
      }
    },
    {
      "Name": "FleeWhenLow",
      "Priority": 60,
      "Sensor": {
        "Type": "And",
        "Sensors": [
          { "Type": "SensorHealth", "Below": 0.25 },
          { "Type": "SensorPlayer", "Range": 15 }
        ]
      },
      "BodyMotion": {
        "Type": "Flee",
        "Target": "Player",
        "Speed": 1.3,
        "SafeDistance": 25
      }
    }
  ]
}
具备多种行为的攻击性生物:
json
{
  "MotionController": "Walk",
  "CombatRange": 2.0,
  "AggroRange": 20,
  "LeashRange": 40,
  
  "DefaultInstruction": {
    "Sensor": { "Type": "Always" },
    "BodyMotion": {
      "Type": "Wander",
      "Speed": 0.4,
      "Radius": 15,
      "IdleTime": { "Min": 2, "Max": 5 }
    },
    "HeadMotion": { "Type": "Nothing" }
  },
  
  "Instructions": [
    {
      "Name": "ReturnToLeash",
      "Priority": 100,
      "Sensor": {
        "Type": "SensorDistance",
        "Target": "LeashPosition",
        "Min": 40
      },
      "BodyMotion": {
        "Type": "MoveTo",
        "Target": "LeashPosition",
        "Speed": 1.5
      }
    },
    {
      "Name": "AttackPlayer",
      "Priority": 50,
      "Sensor": {
        "Type": "And",
        "Sensors": [
          {
            "Type": "SensorPlayer",
            "Range": 2.5,
            "Condition": "Visible"
          },
          {
            "Type": "SensorCooldown",
            "Cooldown": "AttackCooldown",
            "Ready": true
          }
        ]
      },
      "BodyMotion": { "Type": "Stay" },
      "HeadMotion": {
        "Type": "Aim",
        "Target": "Player"
      },
      "Actions": [
        {
          "Type": "Attack",
          "Damage": 8,
          "Animation": "attack_swing"
        },
        {
          "Type": "SetCooldown",
          "Cooldown": "AttackCooldown",
          "Duration": 1.5
        }
      ]
    },
    {
      "Name": "ChasePlayer",
      "Priority": 40,
      "Sensor": {
        "Type": "SensorPlayer",
        "Range": 20,
        "Condition": "Visible"
      },
      "BodyMotion": {
        "Type": "Pursue",
        "Target": "Player",
        "Speed": 1.0,
        "StopDistance": 1.5
      },
      "HeadMotion": {
        "Type": "Watch",
        "Target": "Player"
      }
    },
    {
      "Name": "FleeWhenLow",
      "Priority": 60,
      "Sensor": {
        "Type": "And",
        "Sensors": [
          { "Type": "SensorHealth", "Below": 0.25 },
          { "Type": "SensorPlayer", "Range": 15 }
        ]
      },
      "BodyMotion": {
        "Type": "Flee",
        "Target": "Player",
        "Speed": 1.3,
        "SafeDistance": 25
      }
    }
  ]
}

Entity Spawning

实体生成

Define where and when entities spawn:
定义实体的生成位置与时机:

Spawn Point Configuration

生成点配置

File:
my_creature_spawn.spawn
json
{
  "Entity": "MyPlugin:CustomCreature",
  "SpawnWeight": 10,
  "GroupSize": { "Min": 1, "Max": 3 },
  "SpawnConditions": {
    "Biomes": ["Plains", "Forest"],
    "TimeOfDay": {
      "Start": 0.75,
      "End": 0.25
    },
    "LightLevel": { "Max": 7 },
    "MoonPhase": ["Full", "Waning"],
    "Weather": ["Clear", "Cloudy"],
    "Surface": true
  },
  "SpawnCooldown": 300,
  "MaxNearby": 4,
  "NearbyCheckRadius": 32
}
文件
my_creature_spawn.spawn
json
{
  "Entity": "MyPlugin:CustomCreature",
  "SpawnWeight": 10,
  "GroupSize": { "Min": 1, "Max": 3 },
  "SpawnConditions": {
    "Biomes": ["Plains", "Forest"],
    "TimeOfDay": {
      "Start": 0.75,
      "End": 0.25
    },
    "LightLevel": { "Max": 7 },
    "MoonPhase": ["Full", "Waning"],
    "Weather": ["Clear", "Cloudy"],
    "Surface": true
  },
  "SpawnCooldown": 300,
  "MaxNearby": 4,
  "NearbyCheckRadius": 32
}

Spawn Beacon (Block-based spawning)

生成信标(基于方块的生成)

json
{
  "Type": "Beacon",
  "Entity": "MyPlugin:CustomCreature",
  "SpawnRadius": 10,
  "SpawnInterval": 100,
  "MaxSpawns": 5,
  "DespawnDistance": 64,
  "RequiredBlock": "MyPlugin:SpawnerBlock"
}
json
{
  "Type": "Beacon",
  "Entity": "MyPlugin:CustomCreature",
  "SpawnRadius": 10,
  "SpawnInterval": 100,
  "MaxSpawns": 5,
  "DespawnDistance": 64,
  "RequiredBlock": "MyPlugin:SpawnerBlock"
}

Custom Entity Components

自定义实体组件

Create custom data components:
创建自定义数据组件:

Component Definition

组件定义

java
public class MyEntityData implements Component<EntityStore> {
    public static final BuilderCodec<MyEntityData> CODEC = BuilderCodec.builder(
        Codec.INT.required().fieldOf("Level"),
        Codec.STRING.optionalFieldOf("CustomName", ""),
        Codec.BOOL.optionalFieldOf("IsEnraged", false)
    ).constructor(MyEntityData::new);
    
    private int level;
    private String customName;
    private boolean isEnraged;
    
    public MyEntityData() {
        this(1, "", false);
    }
    
    public MyEntityData(int level, String customName, boolean isEnraged) {
        this.level = level;
        this.customName = customName;
        this.isEnraged = isEnraged;
    }
    
    // Getters and setters
    public int getLevel() { return level; }
    public void setLevel(int level) { this.level = level; }
    public String getCustomName() { return customName; }
    public void setCustomName(String name) { this.customName = name; }
    public boolean isEnraged() { return isEnraged; }
    public void setEnraged(boolean enraged) { this.isEnraged = enraged; }
}
java
public class MyEntityData implements Component<EntityStore> {
    public static final BuilderCodec<MyEntityData> CODEC = BuilderCodec.builder(
        Codec.INT.required().fieldOf("Level"),
        Codec.STRING.optionalFieldOf("CustomName", ""),
        Codec.BOOL.optionalFieldOf("IsEnraged", false)
    ).constructor(MyEntityData::new);
    
    private int level;
    private String customName;
    private boolean isEnraged;
    
    public MyEntityData() {
        this(1, "", false);
    }
    
    public MyEntityData(int level, String customName, boolean isEnraged) {
        this.level = level;
        this.customName = customName;
        this.isEnraged = isEnraged;
    }
    
    // Getters and setters
    public int getLevel() { return level; }
    public void setLevel(int level) { this.level = level; }
    public String getCustomName() { return customName; }
    public void setCustomName(String name) { this.customName = name; }
    public boolean isEnraged() { return isEnraged; }
    public void setEnraged(boolean enraged) { this.isEnraged = enraged; }
}

Component Registration

组件注册

java
@Override
protected void setup() {
    ComponentType<EntityStore, MyEntityData> myDataType = 
        getEntityStoreRegistry().registerComponent(
            MyEntityData.class,
            "myPluginEntityData",
            MyEntityData.CODEC
        );
}
java
@Override
protected void setup() {
    ComponentType<EntityStore, MyEntityData> myDataType = 
        getEntityStoreRegistry().registerComponent(
            MyEntityData.class,
            "myPluginEntityData",
            MyEntityData.CODEC
        );
}

Custom Entity Systems

自定义实体系统

Process entities with matching components:
处理带有匹配组件的实体:

Tick System

Tick系统

java
public class EnrageSystem extends TickSystem<EntityStore> {
    private ComponentAccess<EntityStore, MyEntityData> myData;
    private ComponentAccess<EntityStore, HealthComponent> health;
    
    @Override
    protected void register(Store<EntityStore> store) {
        myData = registerComponent(MyEntityData.class);
        health = registerComponent(HealthComponent.class);
    }
    
    @Override
    public void tick(
        int index,
        ArchetypeChunk<EntityStore> chunk,
        Store<EntityStore> store,
        CommandBuffer<EntityStore> buffer
    ) {
        MyEntityData data = myData.get(chunk, index);
        HealthComponent hp = health.getOptional(chunk, index);
        
        if (hp != null && hp.getPercent() < 0.25f && !data.isEnraged()) {
            data.setEnraged(true);
            // Apply enrage buff
        }
    }
}
java
public class EnrageSystem extends TickSystem<EntityStore> {
    private ComponentAccess<EntityStore, MyEntityData> myData;
    private ComponentAccess<EntityStore, HealthComponent> health;
    
    @Override
    protected void register(Store<EntityStore> store) {
        myData = registerComponent(MyEntityData.class);
        health = registerComponent(HealthComponent.class);
    }
    
    @Override
    public void tick(
        int index,
        ArchetypeChunk<EntityStore> chunk,
        Store<EntityStore> store,
        CommandBuffer<EntityStore> buffer
    ) {
        MyEntityData data = myData.get(chunk, index);
        HealthComponent hp = health.getOptional(chunk, index);
        
        if (hp != null && hp.getPercent() < 0.25f && !data.isEnraged()) {
            data.setEnraged(true);
            // Apply enrage buff
        }
    }
}

Event System

事件系统

java
public class MyDamageHandler extends EntityEventSystem<EntityStore, Damage> {
    private ComponentAccess<EntityStore, MyEntityData> myData;
    
    public MyDamageHandler() {
        super(Damage.class);
    }
    
    @Override
    protected void register(Store<EntityStore> store) {
        myData = registerComponent(MyEntityData.class);
    }
    
    @Override
    public void handle(
        int index,
        ArchetypeChunk<EntityStore> chunk,
        Store<EntityStore> store,
        CommandBuffer<EntityStore> buffer,
        Damage damage
    ) {
        MyEntityData data = myData.getOptional(chunk, index);
        if (data != null && data.isEnraged()) {
            // Reduce damage when enraged
            damage.setAmount(damage.getAmount() * 0.5f);
        }
    }
}
java
public class MyDamageHandler extends EntityEventSystem<EntityStore, Damage> {
    private ComponentAccess<EntityStore, MyEntityData> myData;
    
    public MyDamageHandler() {
        super(Damage.class);
    }
    
    @Override
    protected void register(Store<EntityStore> store) {
        myData = registerComponent(MyEntityData.class);
    }
    
    @Override
    public void handle(
        int index,
        ArchetypeChunk<EntityStore> chunk,
        Store<EntityStore> store,
        CommandBuffer<EntityStore> buffer,
        Damage damage
    ) {
        MyEntityData data = myData.getOptional(chunk, index);
        if (data != null && data.isEnraged()) {
            // Reduce damage when enraged
            damage.setAmount(damage.getAmount() * 0.5f);
        }
    }
}

Entity Registration in Plugin

插件中的实体注册

java
@Override
protected void setup() {
    // Register components
    ComponentType<EntityStore, MyEntityData> dataType = 
        getEntityStoreRegistry().registerComponent(
            MyEntityData.class,
            "myEntityData", 
            MyEntityData.CODEC
        );
    
    // Register systems
    getEntityStoreRegistry().registerSystem(new EnrageSystem());
    getEntityStoreRegistry().registerSystem(new MyDamageHandler());
    
    // Register custom sensors
    getCodecRegistry(Sensor.CODEC).register(
        "MySensor", MySensor.class, MySensor.CODEC
    );
    
    // Register custom actions
    getCodecRegistry(Action.CODEC).register(
        "MyAction", MyAction.class, MyAction.CODEC
    );
}
java
@Override
protected void setup() {
    // Register components
    ComponentType<EntityStore, MyEntityData> dataType = 
        getEntityStoreRegistry().registerComponent(
            MyEntityData.class,
            "myEntityData", 
            MyEntityData.CODEC
        );
    
    // Register systems
    getEntityStoreRegistry().registerSystem(new EnrageSystem());
    getEntityStoreRegistry().registerSystem(new MyDamageHandler());
    
    // Register custom sensors
    getCodecRegistry(Sensor.CODEC).register(
        "MySensor", MySensor.class, MySensor.CODEC
    );
    
    // Register custom actions
    getCodecRegistry(Action.CODEC).register(
        "MyAction", MyAction.class, MyAction.CODEC
    );
}

NPC Interactions

NPC交互

Create interactive NPCs:
json
{
  "DisplayName": { "en-US": "Village Merchant" },
  "Model": "MyPlugin/Models/merchant",
  "Role": "MyPlugin:MerchantRole",
  "IsInteractable": true,
  "Interactions": {
    "Use": "MyPlugin:OpenShop"
  },
  "DialogueTree": "MyPlugin:MerchantDialogue",
  "Schedule": {
    "06:00-18:00": "WorkAtShop",
    "18:00-22:00": "Wander",
    "22:00-06:00": "Sleep"
  }
}
创建可交互NPC:
json
{
  "DisplayName": { "en-US": "Village Merchant" },
  "Model": "MyPlugin/Models/merchant",
  "Role": "MyPlugin:MerchantRole",
  "IsInteractable": true,
  "Interactions": {
    "Use": "MyPlugin:OpenShop"
  },
  "DialogueTree": "MyPlugin:MerchantDialogue",
  "Schedule": {
    "06:00-18:00": "WorkAtShop",
    "18:00-22:00": "Wander",
    "22:00-06:00": "Sleep"
  }
}

Complete Example: Boss Entity

完整示例:Boss实体

json
{
  "DisplayName": {
    "en-US": "Shadow Guardian"
  },
  "Description": {
    "en-US": "Ancient protector of the dark temple"
  },
  "Model": "MyPlugin/Models/shadow_guardian",
  "Scale": 2.0,
  "Health": 500,
  "Armor": 10,
  "AttackDamage": 20,
  "MovementSpeed": 0.8,
  "KnockbackResistance": 0.8,
  "Role": "MyPlugin:ShadowGuardianRole",
  "BossBar": {
    "Enabled": true,
    "Color": "Purple",
    "Style": "Notched"
  },
  "Loot": "MyPlugin:ShadowGuardianLoot",
  "DeathSound": "MyPlugin/Sounds/boss_death",
  "AmbientSound": {
    "Sound": "MyPlugin/Sounds/dark_ambient",
    "Interval": 5
  },
  "Particles": "MyPlugin/Particles/shadow_aura",
  "GlowColor": { "R": 0.5, "G": 0.0, "B": 0.8 },
  "Tags": {
    "Type": ["Boss", "Undead", "Hostile"]
  }
}
json
{
  "DisplayName": {
    "en-US": "Shadow Guardian"
  },
  "Description": {
    "en-US": "Ancient protector of the dark temple"
  },
  "Model": "MyPlugin/Models/shadow_guardian",
  "Scale": 2.0,
  "Health": 500,
  "Armor": 10,
  "AttackDamage": 20,
  "MovementSpeed": 0.8,
  "KnockbackResistance": 0.8,
  "Role": "MyPlugin:ShadowGuardianRole",
  "BossBar": {
    "Enabled": true,
    "Color": "Purple",
    "Style": "Notched"
  },
  "Loot": "MyPlugin:ShadowGuardianLoot",
  "DeathSound": "MyPlugin/Sounds/boss_death",
  "AmbientSound": {
    "Sound": "MyPlugin/Sounds/dark_ambient",
    "Interval": 5
  },
  "Particles": "MyPlugin/Particles/shadow_aura",
  "GlowColor": { "R": 0.5, "G": 0.0, "B": 0.8 },
  "Tags": {
    "Type": ["Boss", "Undead", "Hostile"]
  }
}

Troubleshooting

故障排除

Entity Not Spawning

实体无法生成

  1. Check spawn conditions match environment
  2. Verify spawn weight is > 0
  3. Check MaxNearby limit
  4. Ensure biome/time conditions are met
  1. 检查生成条件是否与环境匹配
  2. 确认生成权重(SpawnWeight)大于0
  3. 检查MaxNearby限制
  4. 确保生物群系/时间条件满足

AI Not Working

AI无法工作

  1. Verify Role reference is correct
  2. Check sensor conditions are achievable
  3. Ensure instruction priorities are ordered
  4. Debug with
    /npc debug
    command
  1. 验证角色(Role)引用是否正确
  2. 检查传感器条件是否可触发
  3. 确保指令优先级顺序正确
  4. 使用
    /npc debug
    命令调试

Components Not Saving

组件无法保存

  1. Ensure CODEC is defined correctly
  2. Register with unique string ID
  3. Check serialization in logs
See
references/entity-components.md
for built-in components. See
references/ai-sensors.md
for all sensor types. See
references/ai-actions.md
for all action types.
  1. 确保CODEC定义正确
  2. 使用唯一字符串ID注册组件
  3. 检查日志中的序列化信息
内置组件请参考
references/entity-components.md
。 所有传感器类型请参考
references/ai-sensors.md
。 所有动作类型请参考
references/ai-actions.md