Minecraft Scripting API

Please note: Some examples on this page may be outdated or may not work as expected.

Entity Spawning & Management

Spawn, control, and manage entities in the world. Entities power everything from boss arenas to NPC systems to particle effects. Master entity manipulation and you can build dynamic, interactive worlds.

Understanding Entities

Entities are interactive objects in the world - anything that moves or has dynamic state: players, mobs, armor stands, thrown items. Unlike static blocks, entities are active:

  • They have health, velocity, position
  • They can be affected by effects (speed, invisibility, etc.)
  • They can hold items and wear armor
  • They trigger events (spawn, death, damage)
  • You get a live reference to them that updates in real-time

Key insight: When you spawn an entity and get a reference, that reference stays valid and reflects the entity's current state. If the entity moves, taking entity.location later gives you the new position.

Key concept: Entities are managed in dimensions (overworld, nether, end). An entity only exists in one dimension at a time.

Spawning Entities

Use spawnEntity to create new entities (mobs, armor stands, item frames) anywhere in the world. You get a reference back that you can immediately customize.

import { world } from "@minecraft/server";

// Get the dimension where you want to spawn (overworld, nether, end)
const dimension = world.getDimension("overworld");

// **Spawn a zombie**
// Returns a reference to the newly created entity
const entity = dimension.spawnEntity("minecraft:zombie", {
  x: 0,          // X coordinate
  y: 64,         // Y coordinate (height)
  z: 0           // Z coordinate
});

// **Spawn other entity types**
const villager = dimension.spawnEntity("minecraft:villager", { x: 10, y: 64, z: 10 });
const armor_stand = dimension.spawnEntity("minecraft:armor_stand", { x: 5, y: 64, z: 5 });

// **Customize the spawned entity immediately**
// Set a custom display name (visible above the entity)
entity.nameTag = "§cZombie Boss"; // §c = red color

// Set health (health component)
// Zombies have default health; you can override it
const health = entity.getComponent("health");
if (health) {
  health.setCurrentValue(50); // Give it 50 health (25 hearts)
}

// **Useful entity types to spawn:**
// minecraft:zombie, minecraft:skeleton, minecraft:creeper - mobs
// minecraft:villager, minecraft:armor_stand - NPCs
// minecraft:item_frame - for decorations
// minecraft:area_effect_cloud - for particle effects or invisible markers

Entity Properties & Movement

Read and modify an entity's live properties - position, velocity, type, dimension, health status.

// **Read entity properties** (these reflect current state)
const pos = entity.location;        // Current {x, y, z} position
console.log(`Entity at: ${pos.x}, ${pos.y}, ${pos.z}`);

const dim = entity.dimension;       // Which dimension (overworld, nether, end)
console.log(`Entity is in: ${dim.id}`);

const typeId = entity.typeId;       // What type of entity ("minecraft:zombie", etc.)
console.log(`Entity type: ${typeId}`);

// **Check if alive** - health component tells us current/max health
const healthComponent = entity.getComponent("health");
const isDead = healthComponent && healthComponent.currentValue <= 0;
const healthPercent = healthComponent 
  ? (healthComponent.currentValue / healthComponent.currentValue) * 100 
  : 0;

// **Get velocity** - how fast and in what direction entity is moving
const velocity = entity.getVelocity();
console.log(`Velocity: ${velocity.x}, ${velocity.y}, ${velocity.z}`);
const speed = Math.sqrt(velocity.x ** 2 + velocity.y ** 2 + velocity.z ** 2);
console.log(`Moving at ${speed} blocks/sec`);

// **Set velocity** - make entity move
// {x: 1, y: 0.5, z: 0} = move 1 block/sec on X axis, 0.5 up, 0 on Z
entity.setVelocity({ x: 1, y: 0.5, z: 0 });

// **Teleport entity** - move to new location (even to different dimension)
// Simple teleport - same dimension
entity.teleport({ x: 100, y: 64, z: 100 });

// Teleport to different dimension
entity.teleport(
  { x: 100, y: 64, z: 100 },
  { dimension: world.getDimension("nether") } // Teleport to Nether at this coordinate
);

Entity Effects (Potions & Buffs)

Apply status effects like Speed, Weakness, Invisibility, Blindness to entities. Effects have duration and amplifier (strength level).

import { EntityEffectType } from "@minecraft/server";

// **Add an effect** - give entity a potion effect
// Parameters: effect type, duration in ticks, options (amplifier)
entity.addEffect(
  EntityEffectType.Speed,           // Speed effect (move faster)
  60,                               // Duration: 60 ticks = 3 seconds
  { amplifier: 2 }                  // Level: Speed II (faster than Speed I)
);

// **Common effects:**
// EntityEffectType.Speed - move faster
// EntityEffectType.Slowness - move slower
// EntityEffectType.Strength - deal more damage
// EntityEffectType.Weakness - deal less damage
// EntityEffectType.Invisibility - become invisible
// EntityEffectType.Blindness - black screen (disorienting)
// EntityEffectType.Regeneration - heal over time
// EntityEffectType.Poison - lose health (but won't kill you)
// EntityEffectType.Instant_Damage - instant damage
// EntityEffectType.Instant_Health - instant heal

// **Get all current effects on entity**
const effects = entity.getEffects();
effects.forEach(effect => {
  console.log(`Effect: ${effect.type}, Duration: ${effect.duration} ticks, Level: ${effect.amplifier}`);
});

// **Remove a specific effect**
// This will clear Poison completely
entity.removeEffect(EntityEffectType.Poison);

// **Practical examples:**

// Give player Speed I for 10 seconds when they stand on special block
if (playerOnSpeedPlate) {
  player.addEffect(EntityEffectType.Speed, 200, { amplifier: 0 }); // 10 seconds
}

// Damage enemy with weakness so next hit does less damage
if (enemyCloseToPlayer) {
  enemy.addEffect(EntityEffectType.Weakness, 100, { amplifier: 0 });
}

// Heal a wounded mob every second until it's at full health
const healthComponent = mob.getComponent("health");
if (healthComponent && healthComponent.currentValue < healthComponent.maxValue) {
  mob.addEffect(EntityEffectType.Regeneration, 20, { amplifier: 1 }); // Regen II for 1 second
}

Equipment & Items

Equip mobs with armor and weapons, or give players items. Useful for boss mechanics, NPC customization, or rewards.

// **Give item to player** (only players have containers)
if (entity.typeId === "minecraft:player") {
  const player = entity;
  const sword = new ItemStack("diamond_sword", 1);
  const success = player.container.addItem(sword);
  
  if (!success) {
    console.log("Inventory full - item not added");
  }
}

// **Equip entity with armor** (works on any entity with equippable component)
// Zombies, skeletons, armor stands, players can all wear armor
const equippable = entity.getComponent("equippable");
if (equippable) {
  // Give helmet
  const helmet = new ItemStack("diamond_helmet", 1);
  equippable.setEquipment(EquipmentSlot.Head, helmet);
  
  // Give chestplate
  const chest = new ItemStack("diamond_chestplate", 1);
  equippable.setEquipment(EquipmentSlot.Chest, chest);
  
  // Give weapon in main hand
  const sword = new ItemStack("diamond_sword", 1);
  equippable.setEquipment(EquipmentSlot.MainHand, sword);
  
  // Give shield in off-hand
  const shield = new ItemStack("shield", 1);
  equippable.setEquipment(EquipmentSlot.OffHand, shield);
}

// **Check what entity is holding**
// const heldItem = equippable.getEquipment(EquipmentSlot.MainHand);
// if (heldItem?.typeId === "diamond_sword") {
//   console.log("Entity has diamond sword equipped");
// }

// **Create a fully-armored boss**
function createArmoredBoss(location) {
  const dimension = world.getDimension("overworld");
  const boss = dimension.spawnEntity("minecraft:zombie", location);
  
  boss.nameTag = "§4Armored Zombie Boss";
  
  const equippable = boss.getComponent("equippable");
  if (equippable) {
    equippable.setEquipment(EquipmentSlot.Head, new ItemStack("diamond_helmet", 1));
    equippable.setEquipment(EquipmentSlot.Chest, new ItemStack("diamond_chestplate", 1));
    equippable.setEquipment(EquipmentSlot.Legs, new ItemStack("diamond_leggings", 1));
    equippable.setEquipment(EquipmentSlot.Feet, new ItemStack("diamond_boots", 1));
    equippable.setEquipment(EquipmentSlot.MainHand, new ItemStack("diamond_sword", 1));
  }
  
  return boss;
}

Damage & Combat

Deal damage to entities, heal them, or modify max health for boss fights and damage systems.

// **Deal damage to an entity**
// Parameters: damage amount, damage source info
entity.applyDamage(10, {  // 10 damage = 5 hearts
  cause: "entityAttack",  // Damage type
  damagingEntity: player  // Who caused the damage (can be null)
});

// **Different damage causes:**
// "entityAttack" - hit by another entity
// "fire" - fire damage
// "fall" - fall damage
// "drowning" - suffocation
// "projectile" - hit by arrow, fireball, etc.
// "magic" - potion effects

// **Heal an entity**
const health = entity.getComponent("health");
if (health) {
  // Get current health and add 5 (2.5 hearts)
  const newHealth = health.currentValue + 5;
  health.setCurrentValue(newHealth);
  
  // Make sure we don't exceed max health
  if (newHealth > health.currentMaxValue) {
    health.setCurrentValue(health.currentMaxValue); // Cap at max
  }
}

// **Set maximum health** (useful for boss fights)
// Zombies normally have 20 health (10 hearts)
// You can increase this for tough bosses
if (health) {
  health.setCurrentMaxValue(100); // Boss with 100 health (50 hearts)
  health.setCurrentValue(100);    // Fill to max
}

// **Practical combat example: custom damage with effects**
function dealSpecialDamage(attacker, victim, amount) {
  // Deal the base damage
  victim.applyDamage(amount, {
    cause: "entityAttack",
    damagingEntity: attacker
  });
  
  // Add weakness effect so victim can't fight back as hard
  victim.addEffect(EntityEffectType.Weakness, 100, { amplifier: 0 });
  
  // Knockback - set victim velocity away from attacker
  const direction = {
    x: victim.location.x - attacker.location.x,
    y: 0,
    z: victim.location.z - attacker.location.z
  };
  const length = Math.sqrt(direction.x ** 2 + direction.z ** 2);
  victim.setVelocity({
    x: (direction.x / length) * 2,
    y: 1,
    z: (direction.z / length) * 2
  });
}

Entity Events

Listen to events when entities spawn, die, or take damage. Perfect for loot drops, stat tracking, or special mechanics.

// **Entity Dies** - triggered when entity's health reaches 0
world.afterEvents.entityDie.subscribe((event) => {
  const entity = event.deadEntity;  // The entity that died
  const damageSource = event.damageSource; // What killed them
  
  // **Drop loot when specific mobs die**
  if (entity.typeId === "minecraft:zombie") {
    const dimension = entity.dimension;
    // Drop rotten flesh at the zombie's location
    dimension.spawnItem(
      new ItemStack("rotten_flesh", 2),
      entity.location
    );
  }
  
  // **Track kills in a database**
  // Could track "zombies killed" stat, award XP, etc.
  // playerData.zombies_killed = (playerData.zombies_killed || 0) + 1;
});

// **Entity Spawns** - triggered when entity is created
// (Either naturally or by spawnEntity call)
world.afterEvents.entitySpawn.subscribe((event) => {
  const entity = event.entity;
  
  // **Customize naturally spawned mobs**
  if (entity.typeId === "minecraft:zombie") {
    entity.nameTag = "§cGreen Zombie"; // Give it a name
    
    // Equip with armor so they're tougher
    const equippable = entity.getComponent("equippable");
    if (equippable) {
      equippable.setEquipment(EquipmentSlot.Head, new ItemStack("iron_helmet", 1));
    }
  }
  
  // **Spawn special events on player spawn**
  if (entity.typeId === "minecraft:player") {
    const player = entity;
    // Could initialize player data, teleport to spawn, etc.
  }
});

// **Entity Hurts** - triggered when any entity takes damage
world.afterEvents.entityHurt.subscribe((event) => {
  const victim = event.hurtEntity;           // Who got hit
  const damage = event.damage;               // How much damage
  const source = event.damageSource;
  const damager = source.damagingEntity;     // Who hit them (could be null)
  
  console.log(`${damager?.typeId || "Unknown"} dealt ${damage} damage to ${victim.typeId}`);
  
  // **Track PvP kills**
  if (damager?.typeId === "minecraft:player" && victim.typeId === "minecraft:player") {
    const attacker = damager;
    console.log(`${attacker.nameTag} hit ${victim.nameTag}`);
    // Could track combat stats, update leaderboards, etc.
  }
  
  // **Apply knockback or effects on hit**
  // if (damage > 5) {
  //   victim.addEffect(EntityEffectType.Slowness, 40, { amplifier: 0 });
  // }
});

Particle Effects

Spawn visual effects at locations - explosions, flames, hearts, etc. Great for feedback, visual flair, or marking special locations.

const dimension = world.getDimension("overworld");

// **Spawn a single particle** at a location
// Particles are visual-only (don't affect gameplay)
dimension.spawnParticle(
  "minecraft:explosion_particle", // Particle type
  { x: 0, y: 64, z: 0 }           // Location
);

// **Multiple particles** - spawn a burst effect
// Useful for highlighting locations or visual feedback
for (let i = 0; i < 20; i++) {
  dimension.spawnParticle(
    "minecraft:flame",  // Fire particles
    {
      x: 0 + Math.random() * 10,    // Spread around X
      y: 64 + Math.random() * 5,    // Spread around Y
      z: 0 + Math.random() * 10     // Spread around Z
    }
  );
}

// **Common particle types:**
// "minecraft:explosion_particle" - explosion
// "minecraft:flame" - fire/flames
// "minecraft:smoke" - smoke
// "minecraft:water_splash" - water splash
// "minecraft:critical_hit" - damage numbers (when attacking)
// "minecraft:enchanting_table_particle" - magic sparkles
// "minecraft:dripping_water" - water drips
// "minecraft:item_crack" - broken item particles

// **Practical examples:**

// Teleport effect - particles at start and end location
function teleportWithEffect(entity, destination) {
  // Particles at starting location
  for (let i = 0; i < 15; i++) {
    entity.dimension.spawnParticle("minecraft:water_splash", entity.location);
  }
  
  // Teleport
  entity.teleport(destination);
  
  // Particles at destination
  for (let i = 0; i < 15; i++) {
    entity.dimension.spawnParticle("minecraft:enchanting_table_particle", destination);
  }
}

// Boss damage indicator - show where boss took damage
function showDamageEffect(entity) {
  for (let i = 0; i < 10; i++) {
    entity.dimension.spawnParticle("minecraft:critical_hit", entity.location);
  }
}

Entity Queries

Find entities in the world by type, location, or custom filters. Essential for arena mechanics, proximity triggers, and mob management.

const dimension = world.getDimension("overworld");

// **Get all entities** - returns every entity in the dimension
const allEntities = dimension.getEntities();
console.log(`Total entities: ${allEntities.length}`);

// **Get entities of specific type** - filter by entity type
const zombies = dimension.getEntities({
  type: "minecraft:zombie"  // Only get zombies
});
console.log(`Zombies in world: ${zombies.length}`);

// **Get entities in range** - find nearby entities
// Useful for proximity triggers, arena mechanics, AI behaviors
const playersNearby = dimension.getEntities({
  type: "minecraft:player",
  location: { x: 0, y: 64, z: 0 }, // Center of search
  maxDistance: 50                    // 50 block radius
});
console.log(`Players within 50 blocks: ${playersNearby.length}`);

// **Filter results** - get only entities meeting criteria
// e.g., get only living zombies (health > 0)
const allZombies = dimension.getEntities({ type: "minecraft:zombie" });
const livingZombies = allZombies.filter(entity => {
  const health = entity.getComponent("health");
  return health && health.currentValue > 0;
});

// **Practical examples:**

// Get all players within 50 blocks of a location
function getNearbyPlayers(location, radius) {
  return dimension.getEntities({
    type: "minecraft:player",
    location,
    maxDistance: radius
  });
}

// Count hostile mobs near player (for difficulty)
function getHostileMobCount(playerLocation) {
  const hostileMobs = ["minecraft:zombie", "minecraft:skeleton", "minecraft:creeper"];
  let count = 0;
  
  for (const mobType of hostileMobs) {
    const mobs = dimension.getEntities({
      type: mobType,
      location: playerLocation,
      maxDistance: 100
    });
    count += mobs.length;
  }
  
  return count;
}

// Get all mobs in arena (to check if arena is clear)
function getArenaHealth(arenaCenter, arenaRadius) {
  const mobs = dimension.getEntities({
    location: arenaCenter,
    maxDistance: arenaRadius
  }).filter(e => e.typeId !== "minecraft:player"); // Exclude players
  
  return mobs.length > 0 ? "In progress" : "Clear";
}

// Find the closest zombie to a player
function findNearestZombie(player) {
  const zombies = dimension.getEntities({ type: "minecraft:zombie" });
  
  let nearest = null;
  let nearestDistance = Infinity;
  
  for (const zombie of zombies) {
    const dx = zombie.location.x - player.location.x;
    const dy = zombie.location.y - player.location.y;
    const dz = zombie.location.z - player.location.z;
    const distance = Math.sqrt(dx ** 2 + dy ** 2 + dz ** 2);
    
    if (distance < nearestDistance) {
      nearest = zombie;
      nearestDistance = distance;
    }
  }
  
  return nearest;
}
Navigation