Skip to main content

Overview

The Player API provides functionality for player entities in Minecraft Community Edition, including movement, inventory management, abilities, experience, food, and multiplayer synchronization.

Class Hierarchy

Entity
  └── Mob
        └── Player
              ├── LocalPlayer (client-side)
              └── MultiplayerLocalPlayer (client multiplayer)

Player Class

Represents a player entity in the game. Header: Minecraft.World/Player.h
Inherits: Mob, CommandSender

Constants

static const int MAX_NAME_LENGTH = 20;      // 16 + 4
static const int MAX_HEALTH = 20;
static const int SWING_DURATION = 6;
static const int SLEEP_DURATION = 100;
static const int WAKE_UP_DURATION = 10;
static const int DEATHFADE_DURATION = 21;

// Chat visibility
static const int CHAT_VISIBILITY_FULL = 0;
static const int CHAT_VISIBILITY_SYSTEM = 1;
static const int CHAT_VISIBILITY_HIDDEN = 2;

Core Members

shared_ptr<Inventory> inventory;           // Player inventory (hotbar + main)
Abilities abilities;                       // Flight, invulnerability, etc.

wstring name;                              // Player username
wstring displayName;                       // Display name (Xbox Live, PSN)
int dimension;                             // Current dimension ID

int score;                                 // Player score (death counter)
int experienceLevel;                       // XP level (enchanting)
int totalExperience;                       // Total XP earned
float experienceProgress;                  // Progress to next level (0-1)

Stats *stats;                              // Statistics and achievements

bool swinging;                             // Is arm swinging?
int swingTime;                             // Swing animation timer

AbstractContainerMenu *inventoryMenu;      // Player inventory UI
AbstractContainerMenu *containerMenu;      // Current open container

Constructor

Player(Level* level)
constructor
Creates a new player in the specified world.Parameters:
  • level - World to spawn player in

Inventory & Items

getSelectedItem()
shared_ptr<ItemInstance>
Gets the currently selected/held item.Returns: Item in selected hotbar slot, or null
removeSelectedItem()
void
Removes one of the selected item from inventory.
getArmor(int pos)
shared_ptr<ItemInstance>
Gets armor piece at slot.Parameters:
  • pos - Armor slot (0=helmet, 1=chest, 2=legs, 3=boots)
getArmorValue()
int
Gets total armor defense points.Returns: Defense value (0-20)
getArmorCoverPercentage()
float
Gets armor coverage as percentage.Returns: Coverage (0.0-1.0)
getInventorySlot(int slotId)
Slot*
Gets inventory slot by ID.Parameters:
  • slotId - Slot index

Item Usage

getUseItem()
shared_ptr<ItemInstance>
Gets item currently being used (eating, blocking, etc.).
getUseItemDuration()
int
Gets ticks remaining for item use.
isUsingItem()
bool
Checks if player is using an item.
getTicksUsingItem()
int
Gets ticks item has been in use.
startUsingItem(shared_ptr<ItemInstance> instance, int duration)
void
Begins using an item.Parameters:
  • instance - Item to use
  • duration - Max use duration in ticks
stopUsingItem()
void
Cancels item usage.
releaseUsingItem()
void
Completes item usage (bow release, finish eating).
isBlocking()
bool
Checks if player is blocking with shield/sword.

Movement & Abilities

travel(float xa, float ya)
void
Handles player movement input.Parameters:
  • xa - Strafe input (-1 to 1)
  • ya - Forward input (-1 to 1)
abilities
Abilities
Player abilities structure:
struct Abilities {
    bool invulnerable;     // Cannot take damage
    bool flying;           // Currently flying
    bool canFly;          // Can toggle flight
    bool instabuild;      // Instant block breaking
    bool canBuild;        // Can place/break blocks
    float flyingSpeed;    // Flight speed multiplier
    float walkingSpeed;   // Walk speed multiplier
};
onUpdateAbilities()
void
Called when abilities are updated.Note: Override to sync abilities in multiplayer

Combat

swing()
void
Plays arm swing animation.
attack(shared_ptr<Entity> entity)
void
Attacks an entity.Parameters:
  • entity - Target to attack
crit(shared_ptr<Entity> entity)
void
Plays critical hit effects.
magicCrit(shared_ptr<Entity> entity)
void
Plays magic critical hit effects (enchanted weapon).
getDestroySpeed(Tile* tile)
float
Gets block breaking speed multiplier.Returns: Speed based on tool, enchantments, effects
canDestroy(Tile* tile)
bool
Checks if player can break this block type.

Health & Damage

getMaxHealth()
int
Gets maximum health.Returns: 20 (10 hearts) by default
hurt(DamageSource* source, int dmg)
bool
Applies damage to player.Parameters:
  • source - Damage source
  • dmg - Damage amount
Returns: true if damage was applied
die(DamageSource* source)
void
Handles player death.Parameters:
  • source - Cause of death
respawn()
void
Respawns player at spawn point.
isHurt()
bool
Checks if player is hurt (health < max).

Food & Exhaustion

getFoodData()
FoodData*
Gets food/hunger data.Returns: Pointer to FoodData structure
canEat(bool magicalItem)
bool
Checks if player can eat.Parameters:
  • magicalItem - Can eat even when full? (golden apple)
causeFoodExhaustion(float amount)
void
Adds exhaustion (decreases food over time).Parameters:
  • amount - Exhaustion amount
Examples: 0.025 per meter walked, 0.1 per meter sprinted

Experience

increaseXp(int i)
void
Adds experience points.Parameters:
  • i - XP amount to add
withdrawExperienceLevels(int amount)
void
Removes experience levels.Parameters:
  • amount - Levels to remove
Use case: Enchanting, anvil repairs
getXpNeededForNextLevel()
int
Gets XP needed to reach next level.Returns: XP requirement for current level

Sleeping

startSleepInBed(int x, int y, int z, bool testUse)
BedSleepingResult
Attempts to sleep in a bed.Parameters:
  • x, y, z - Bed position
  • testUse - Only test, don’t actually sleep
Returns: Result enum (OK, NOT_POSSIBLE_NOW, TOO_FAR_AWAY, etc.)
stopSleepInBed(bool forcefulWakeUp, bool updateLevelList, bool saveRespawnPoint)
void
Wakes player from bed.Parameters:
  • forcefulWakeUp - Skip wake animation
  • updateLevelList - Update world’s sleeping player list
  • saveRespawnPoint - Set spawn to this bed
isSleeping()
bool
Checks if player is sleeping.
isSleepingLongEnough()
bool
Checks if player has slept long enough to skip night.
getSleepTimer()
int
Gets sleep animation timer.
getRespawnPosition()
Pos*
Gets bed respawn position.
setRespawnPosition(Pos* respawnPosition)
void
Sets respawn point.

Containers & Interaction

openContainer(shared_ptr<Container> container)
bool
Opens a container inventory.Returns: true if opened successfully
openFurnace(shared_ptr<FurnaceTileEntity> container)
bool
Opens furnace UI.
openTrap(shared_ptr<DispenserTileEntity> container)
bool
Opens dispenser/dropper UI.
openBrewingStand(shared_ptr<BrewingStandTileEntity> brewingStand)
bool
Opens brewing stand UI.
openTrading(shared_ptr<Merchant> traderTarget)
bool
Opens trading UI with villager.
startEnchanting(int x, int y, int z)
bool
Opens enchantment table UI.
startCrafting(int x, int y, int z)
bool
Opens crafting table UI.
closeContainer()
void
Closes current container.

Dropping Items

drop()
shared_ptr<ItemEntity>
Drops selected item stack.
drop(shared_ptr<ItemInstance> item)
shared_ptr<ItemEntity>
Drops specific item.
drop(shared_ptr<ItemInstance> item, bool randomly)
shared_ptr<ItemEntity>
Drops item with optional randomized position.

Statistics

awardStat(Stat* stat, byteArray param)
void
Awards a statistic/achievement.Parameters:
  • stat - Statistic to increment
  • param - Additional data
getScore()
int
Gets player score.Returns: Score value (used as death counter)

Identity & Customization

getName()
wstring
Gets player username.
getDisplayName()
wstring
Gets display name (console gamertag/PSN ID).
getXuid()
PlayerUID
Gets Xbox User ID (XUID).
setXuid(PlayerUID xuid)
void
Sets XUID.
getUUID()
wstring
Gets unique player UUID.
setCustomSkin(DWORD skinId)
void
Sets custom player skin.
getCustomSkin()
DWORD
Gets current custom skin ID.
setCustomCape(DWORD capeId)
void
Sets custom cape.

Permissions & Privileges

enum EPlayerGamePrivileges {
    ePlayerGamePrivilege_CannotMine,
    ePlayerGamePrivilege_CannotBuild,
    ePlayerGamePrivilege_CannotAttackMobs,
    ePlayerGamePrivilege_CannotAttackPlayers,
    ePlayerGamePrivilege_Op,
    ePlayerGamePrivilege_CanFly,
    ePlayerGamePrivilege_ClassicHunger,
    ePlayerGamePrivilege_Invisible,
    ePlayerGamePrivilege_Invulnerable,
    // ... more
};
isAllowedToMine()
bool
Checks if player can break blocks.
isAllowedToAttackPlayers()
bool
Checks if PvP is allowed for this player.
isAllowedToFly()
bool
Checks if flight is allowed.
isModerator()
bool
Checks if player has operator privileges.
setPlayerGamePrivilege(EPlayerGamePrivileges privilege, unsigned int value)
void
Sets a privilege flag.

Dimension Travel

changeDimension(int i)
void
Teleports player to another dimension.Parameters:
  • i - Dimension ID (0=Overworld, -1=Nether, 1=End)
handleInsidePortal()
void
Handles portal travel timer.
isInsidePortal
bool
Is player standing in a portal?
portalTime
float
Portal animation timer (0-1).

MultiplayerLocalPlayer Class

Client-side multiplayer player with network synchronization. Header: Minecraft.Client/MultiplayerLocalPlayer.h
Inherits: LocalPlayer

Constructor

MultiplayerLocalPlayer(Minecraft*, Level*, User*, ClientConnection*)
constructor
Creates a multiplayer client player.Parameters:
  • minecraft - Game instance
  • level - World
  • user - User profile
  • connection - Server connection

Network Synchronization

sendPosition()
void
Sends position/rotation update to server.Note: Called automatically when position changes significantly
tick()
void
Updates player and sends position packets.Automatically sends position every 20 ticks or when changed.

Methods

chat(const wstring& message)
void
Sends chat message to server.
swing()
void
Swings arm and notifies server.
respawn()
void
Requests respawn from server.
hurtTo(int newHealth, ETelemetryChallenges damageSource)
void
Sets health from server update.Parameters:
  • newHealth - New health value
  • damageSource - Source of damage for telemetry

Example Usage

Basic Player Access

// Get player from level
auto player = level->players[0];

// Check player state
if (player->isSleeping()) {
    player->stopSleepInBed(false, true, true);
}

// Get player name
wstring name = player->getName();

Inventory Manipulation

// Get held item
auto heldItem = player->getSelectedItem();
if (heldItem) {
    int itemId = heldItem->id;
    int count = heldItem->count;
}

// Check armor
int totalArmor = player->getArmorValue();
auto helmet = player->getArmor(0);

Experience & Levels

// Award XP
player->increaseXp(50);

// Check level
if (player->experienceLevel >= 30) {
    // Can enchant at level 30
}

// Get progress to next level
float progress = player->experienceProgress;  // 0.0 - 1.0

Combat & Damage

// Attack entity
if (auto target = dynamic_pointer_cast<Entity>(targetEntity)) {
    player->attack(target);
    
    // Critical hit?
    if (player->fallDistance > 0 && !player->onGround) {
        player->crit(target);
    }
}

// Apply damage
auto source = new EntityDamageSource("mob", attacker);
player->hurt(source, 5);

Movement & Abilities

// Enable flight
player->abilities.canFly = true;
player->abilities.flying = true;
player->onUpdateAbilities();

// Set speed
player->abilities.flyingSpeed = 0.1f;
player->abilities.walkingSpeed = 0.2f;

Food & Hunger

// Get food data
auto food = player->getFoodData();
int foodLevel = food->getFoodLevel();      // 0-20
float saturation = food->getSaturation();

// Add exhaustion (mining, sprinting, etc.)
player->causeFoodExhaustion(0.025f);

// Check if can eat
if (player->canEat(false)) {
    // Start eating
}

See Also

  • Entity API - Base entity functionality
  • Mob API - Living entity features
  • Level API - Player management in worlds
  • Inventory API - Item and container management

Build docs developers (and LLMs) love