Class FakePlayer
- All Implemented Interfaces:
Attackable
,CommandOutput
,Nameable
,EntityLike
ServerPlayerEntity
that is not a human player.
They are typically used to automatically perform player actions such as placing blocks.
The easiest way to obtain a fake player is with get(ServerWorld)
or get(ServerWorld, GameProfile)
.
It is also possible to create a subclass for more control over the fake player's behavior.
For good inter-mod compatibility, fake players should have the UUID of their owning (human) player.
They should still have a different name to ensure the GameProfile
is different.
For example:
UUID humanPlayerUuid = ...;
String humanPlayerName = ...;
GameProfile fakeProfile = new GameProfile(humanPlayerUuid, "[Block Breaker of " + humanPlayerName + "]");
If a fake player does not belong to a specific player, the default UUID
should be used.
Fake players try to behave like regular ServerPlayerEntity
objects to a reasonable extent.
In some edge cases, or for gameplay considerations, it might be necessary to check whether a ServerPlayerEntity
is a fake player.
This can be done with an instanceof
check: player instanceof FakePlayer
.
-
Nested Class Summary
Nested classes/interfaces inherited from class net.minecraft.entity.player.PlayerEntity
PlayerEntity.SleepFailureReason
Nested classes/interfaces inherited from class net.minecraft.entity.LivingEntity
LivingEntity.FallSounds
Nested classes/interfaces inherited from class net.minecraft.entity.Entity
Entity.MoveEffect, Entity.PositionUpdater, Entity.RemovalReason
-
Field Summary
Modifier and TypeFieldDescriptionstatic final UUID
Default UUID, for fake players not associated with a specific (human) player.Fields inherited from class net.minecraft.server.network.ServerPlayerEntity
interactionManager, networkHandler, notInAnyWorld, pingMilliseconds, server
Fields inherited from class net.minecraft.entity.player.PlayerEntity
abilityResyncCountdown, capeX, capeY, capeZ, currentScreenHandler, damageTiltYaw, DEFAULT_EYE_HEIGHT, enchantmentTableSeed, enderChestInventory, experienceLevel, experiencePickUpDelay, experienceProgress, field_30643, field_30644, field_30645, field_30646, field_30647, field_30648, field_30649, field_30650, field_7509, fishHook, hungerManager, isSubmergedInWater, LEFT_SHOULDER_ENTITY, MAIN_ARM, PLAYER_MODEL_PARTS, playerScreenHandler, prevCapeX, prevCapeY, prevCapeZ, prevStrideDistance, RIGHT_SHOULDER_ENTITY, STANDING_DIMENSIONS, strideDistance, totalExperience
Fields inherited from class net.minecraft.entity.LivingEntity
activeItemStack, attackingPlayer, BABY_SCALE_FACTOR, bodyTrackingIncrements, bodyYaw, brain, dead, DEATH_TICKS, deathTime, defaultMaxHealth, despawnCounter, EQUIPMENT_SLOT_ID, field_30063, field_30067, field_30069, field_30070, field_30072, field_30074, field_30075, field_6215, forwardSpeed, GLOWING_FLAG, GRAVITY, handSwinging, handSwingProgress, handSwingTicks, headTrackingIncrements, headYaw, hurtTime, itemUseTimeLeft, jumping, lastAttackedTicks, lastDamageTaken, lastHandSwingProgress, limbAnimator, LIVING_FLAGS, lookDirection, maxHurtTime, OFF_HAND_ACTIVE_FLAG, playerHitTimer, preferredHand, prevBodyYaw, prevHeadYaw, prevLookDirection, prevStepBobbingAmount, randomLargeSeed, randomSmallSeed, riptideTicks, roll, scoreAmount, serverHeadYaw, serverPitch, serverX, serverY, serverYaw, serverZ, sidewaysSpeed, SLEEPING_DIMENSIONS, stepBobbingAmount, stuckArrowTimer, stuckStingerTimer, upwardSpeed, USING_ITEM_FLAG, USING_RIPTIDE_FLAG
Fields inherited from class net.minecraft.entity.Entity
age, collidedSoftly, dataTracker, DEFAULT_FRICTION, DEFAULT_MIN_FREEZE_DAMAGE_TICKS, DEFAULT_PORTAL_COOLDOWN, distanceTraveled, FALL_FLYING_FLAG_INDEX, fallDistance, field_29991, field_44870, field_44871, field_44872, firstUpdate, FLAGS, fluidHeight, FREEZING_DAMAGE_INTERVAL, GLOWING_FLAG_INDEX, groundCollision, horizontalCollision, horizontalSpeed, ID_KEY, ignoreCameraFrustum, inNetherPortal, inPowderSnow, intersectionChecked, lastNetherPortalPosition, lastRenderX, lastRenderY, lastRenderZ, MAX_COMMAND_TAGS, MAX_RIDING_COOLDOWN, MIN_RISING_BUBBLE_COLUMN_SPEED, movementMultiplier, netherPortalTime, noClip, ON_FIRE_FLAG_INDEX, PASSENGERS_KEY, POSE, prevHorizontalSpeed, prevPitch, prevX, prevY, prevYaw, prevZ, random, ridingCooldown, speed, submergedInWater, supportingBlockPos, timeUntilRegen, touchingWater, uuid, UUID_KEY, uuidString, velocityDirty, velocityModified, verticalCollision, wasInPowderSnow, wasOnFire
Fields inherited from interface net.minecraft.server.command.CommandOutput
DUMMY
-
Constructor Summary
ModifierConstructorDescriptionprotected
FakePlayer
(ServerWorld world, com.mojang.authlib.GameProfile profile) -
Method Summary
Modifier and TypeMethodDescriptionstatic FakePlayer
get
(ServerWorld world) Retrieves a fake player for the specified world, using thedefault UUID
.static FakePlayer
get
(ServerWorld world, com.mojang.authlib.GameProfile profile) Retrieves a fake player for the specified world and game profile.@Nullable AbstractTeam
void
increaseStat
(Stat<?> stat, int amount) boolean
isInvulnerableTo
(DamageSource damageSource) void
openEditSignScreen
(SignBlockEntity sign, boolean front) openHandledScreen
(@Nullable NamedScreenHandlerFactory factory) void
openHorseInventory
(AbstractHorseEntity horse, Inventory inventory) void
void
void
boolean
startRiding
(Entity entity, boolean force) void
tick()
Methods inherited from class net.minecraft.server.network.ServerPlayerEntity
addCritParticles, addEnchantedHitParticles, addExperience, addExperienceLevels, allowsServerListing, applyEnchantmentCosts, applyMovementEffects, areClientChatColorsEnabled, attack, canBeSpectated, canModifyAt, changeGameMode, closeHandledScreen, consumeItem, copyFrom, createCooldownManager, createSpawnPacket, damage, dropItem, dropSelectedItem, endCombat, enterCombat, fall, getAdvancementTracker, getCameraEntity, getClientChatVisibility, getIp, getLastActionTime, getPermissionLevel, getPlayerListName, getPortalRect, getRecipeBook, getSculkShriekerWarningManager, getServerWorld, getSession, getSpawnAngle, getSpawnPointDimension, getSpawnPointPosition, getStatHandler, getTeleportTarget, getTextStream, getWatchedSection, handleFall, isCreative, isDisconnected, isInTeleportationState, isSpawnForced, isSpectator, lockRecipes, lookAt, lookAtEntity, markHealthDirty, moveToWorld, onBlockCollision, onDeath, onDisconnect, onHandledScreenClosed, onLanding, onSpawn, onStatusEffectApplied, onStatusEffectRemoved, onStatusEffectUpgraded, onTeleportationDone, openCommandBlockScreen, playerTick, playSound, readCustomDataFromNbt, refreshPositionAfterTeleport, requestTeleport, requestTeleportAndDismount, requestTeleportOffset, sendAbilitiesUpdate, sendChatMessage, sendChunkPacket, sendMessage, sendMessage, sendMessageToClient, sendPickup, sendResourcePackUrl, sendServerMetadata, sendTradeOffers, sendUnloadChunkPacket, setCameraEntity, setExperienceLevel, setExperiencePoints, setGameMode, setServerWorld, setSession, setSpawnPoint, setWatchedSection, shouldDamagePlayer, shouldFilterMessagesSentTo, shouldFilterText, stopRiding, swingHand, teleport, teleport, tickFallStartPos, tickItemStackUsage, tickPortalCooldown, tickVehicleInLavaRiding, tiltScreen, triggerItemPickedUpByEntityCriteria, trySleep, unlockCraftedRecipe, unlockRecipes, unlockRecipes, updateInput, updateKilledAdvancementCriterion, updateLastActionTime, updatePotionVisibility, useBook, wakeUp, writeCustomDataToNbt
Methods inherited from class net.minecraft.entity.player.PlayerEntity
addExhaustion, addScore, addShoulderEntity, adjustMovementForSneaking, animateDamage, applyDamage, attackLivingEntity, canBeHitByProjectile, canConsume, canEquip, canFoodHeal, canHarvest, canModifyBlocks, canPlaceOn, canResetTimeBySleeping, canSprintAsVehicle, canTakeDamage, checkFallFlying, clipAtLedge, createPlayerAttributes, damageArmor, damageHelmet, damageShield, disableShield, dismountVehicle, doesNotSuffocate, dropInventory, dropItem, dropShoulderEntities, eatFood, equipStack, findRespawnPosition, getAbilities, getAbsorptionAmount, getActiveEyeHeight, getArmorItems, getAttackCooldownProgress, getAttackCooldownProgressPerTick, getBlockBreakingSpeed, getBurningDuration, getDamageTiltYaw, getDeathSound, getDefaultPortalCooldown, getDimensions, getDisplayName, getEnchantmentTableSeed, getEnderChestInventory, getEntityName, getEquippedStack, getFallSounds, getGameProfile, getHandItems, getHeightOffset, getHighSpeedSplashSound, getHungerManager, getHurtSound, getInventory, getItemCooldownManager, getLastDeathPos, getLeashPos, getLuck, getMainArm, getMaxNetherPortalTime, getMoveEffect, getMovementSpeed, getName, getNextLevelExperience, getOffGroundSpeed, getPoses, getProjectileType, getScore, getScoreboard, getShoulderEntityLeft, getShoulderEntityRight, getSleepTimer, getSoundCategory, getSplashSound, getStackReference, getSwimSound, getVelocityMultiplier, getXpToDrop, giveItemStack, handleFallDamage, handleStatus, hasReducedDebugInfo, increaseStat, increaseTravelMotionStats, incrementStat, incrementStat, initDataTracker, interact, isArmorSlot, isBlockBreakingRestricted, isCreativeLevelTwoOp, isImmobile, isMainPlayer, isOnSoulSpeedBlock, isPartVisible, isPlayer, isPushedByFluids, isSwimming, isUsingSpyglass, jump, onKilledOther, onPickupSlotClick, onSwimmingStart, openCommandBlockMinecartScreen, openJigsawScreen, openStructureBlockScreen, playSound, playStepSound, remove, requestRespawn, resetLastAttackedTicks, setAbsorptionAmount, setFireTicks, setLastDeathPos, setMainArm, setReducedDebugInfo, setScore, setShoulderEntityLeft, setShoulderEntityRight, shouldAlwaysDropXp, shouldCancelInteraction, shouldCloseHandledScreenOnRespawn, shouldDismount, shouldRemoveSoulSpeedBoost, shouldRenderName, shouldSave, shouldSwimInFluids, slowMovement, spawnSweepAttackParticles, startFallFlying, stopFallFlying, takeShieldHit, tickMovement, tickNewAi, tickRiding, travel, updatePose, updateSwimming, updateWaterSubmersionState, useRiptide, vanishCursedItems, wakeUp
Methods inherited from class net.minecraft.entity.LivingEntity
addPowderSnowSlowIfNeeded, addSoulSpeedBoostIfNeeded, addStatusEffect, addStatusEffect, applyArmorToDamage, applyFluidMovingSpeed, applyMovementInput, areItemsDifferent, baseTick, blockedByShield, canBreatheInWater, canFreeze, canHaveStatusEffect, canHit, canSee, canTarget, canTarget, canUsePortals, canWalkOnFluid, clearActiveItem, clearPotionSwirls, clearSleepingPosition, clearStatusEffects, computeFallDamage, containsOnlyAmbientEffects, createBrainProfile, createLivingAttributes, deserializeBrain, disableExperienceDropping, disablesShield, displaySoulSpeedEffects, drop, dropEquipment, dropLoot, dropXp, getActiveHand, getActiveItem, getActiveStatusEffects, getArmor, getArmorVisibility, getAttackDistanceScalingFactor, getAttacker, getAttacking, getAttackPos, getAttributeBaseValue, getAttributeBaseValue, getAttributeInstance, getAttributes, getAttributeValue, getAttributeValue, getBaseMovementSpeedMultiplier, getBodyYaw, getBoundingBox, getBrain, getClimbingPos, getControlledMovementInput, getDamageTracker, getDespawnCounter, getDrinkSound, getEatSound, getEyeHeight, getGroup, getHandSwingProgress, getHeadYaw, getHealth, getItemUseTime, getItemUseTimeLeft, getJumpBoostVelocityModifier, getJumpVelocity, getLastAttackedTime, getLastAttacker, getLastAttackTime, getLeaningPitch, getLootTable, getLootTableSeed, getMainHandStack, getMaxHealth, getNextAirOnLand, getNextAirUnderwater, getOffHandStack, getPreferredEquipmentSlot, getPrimeAdversary, getRandom, getRecentDamageSource, getRoll, getSaddledSpeed, getScaleFactor, getSleepingDirection, getSleepingPosition, getSoundPitch, getSoundVolume, getStackInHand, getStatusEffect, getStatusEffects, getStepHeight, getStingerCount, getStuckArrowCount, getVisibilityBoundingBox, getYaw, hasNoDrag, hasStackEquipped, hasStatusEffect, heal, hurtByWater, isAffectedBySplashPotions, isAlive, isBaby, isBlocking, isClimbing, isDead, isExperienceDroppingDisabled, isFallFlying, isGlowing, isHolding, isHolding, isHoldingOntoLadder, isInsideWall, isInSwimmingPose, isMobOrPlayer, isPartOfGame, isPushable, isSleeping, isTarget, isUndead, isUsingItem, isUsingRiptide, kill, knockback, knockDownwards, markEffectsDirty, modifyAppliedDamage, onAttacking, onDamaged, onEquipStack, onKilledBy, onSpawnPacket, onTrackedDataSet, playBlockFallSound, playHurtSound, positionInPortal, positionInPortal, processEquippedStack, pushAway, pushAwayFrom, removePowderSnowSlow, removeSoulSpeedBoost, removeStatusEffect, removeStatusEffectInternal, sendEffectToControllingPlayer, sendEquipmentBreakStatus, sendToolBreakStatus, setAttacker, setAttacking, setBodyYaw, setCurrentHand, setDespawnCounter, setHeadYaw, setHealth, setJumping, setLivingFlag, setMovementSpeed, setNearbySongPlaying, setNoDrag, setSleepingPosition, setSprinting, setStackInHand, setStatusEffect, setStingerCount, setStuckArrowCount, shouldDisplaySoulSpeedEffects, shouldDropLoot, shouldDropXp, spawnConsumptionEffects, stopUsingItem, swimUpward, swingHand, takeKnockback, teleport, tickControlled, tickCramming, tickHandSwing, tickInVoid, tickRiptide, tickStatusEffects, tryAttack, turnHead, updateLimbs, updateLimbs, updatePostDeath, updateTrackedHeadRotation, updateTrackedPositionAndAngles
Methods inherited from class net.minecraft.entity.Entity
addAirTravelEffects, addCommandTag, addFlapEffects, addPassenger, addVelocity, addVelocity, adjustMovementForCollisions, adjustMovementForPiston, applyDamageEffects, applyMirror, applyRotation, attemptTickInVoid, bypassesLandingEffects, bypassesSteppingEffects, calculateBoundingBox, calculateBoundsForPose, calculateDimensions, calculateNextStepSoundDistance, canAddPassenger, canAvoidTraps, canExplosionDestroyBlock, canMoveVoluntarily, canStartRiding, changeLookDirection, checkBlockCollision, checkDespawn, collidesWith, collidesWithStateAtPos, copyFrom, copyPositionAndRotation, couldAcceptPassenger, detach, discard, distanceTo, doesNotCollide, doesRenderOnFire, dropItem, dropItem, dropStack, dropStack, emitGameEvent, emitGameEvent, entityDataRequiresOperator, equals, extinguish, extinguishWithSound, getAir, getBlockPos, getBlockStateAtPos, getBlockX, getBlockY, getBlockZ, getBodyY, getBoundingBox, getBrightnessAtEyes, getCameraPosVec, getChunkPos, getClientCameraPosVec, getCommandSource, getCommandTags, getControllingPassenger, getControllingVehicle, getCustomName, getDamageSources, getDataTracker, getDefaultName, getEffectiveExplosionResistance, getEntityWorld, getEyeHeight, getEyePos, getEyeY, getFireTicks, getFirstPassenger, getFlag, getFluidHeight, getFreezingScale, getFrozenTicks, getHandPosOffset, getHeight, getHorizontalFacing, getHoverEvent, getId, getItemsEquipped, getJumpVelocityMultiplier, getLandingBlockState, getLandingPos, getLeashOffset, getLeashOffset, getLerpedPos, getMaxAir, getMinFreezeDamageTicks, getMountedHeightOffset, getMovementDirection, getNameLabelHeight, getOppositeRotationVector, getOppositeRotationVector, getParticleX, getParticleZ, getPassengerDismountOffset, getPassengerList, getPassengersDeep, getPickBlockStack, getPistonBehavior, getPitch, getPitch, getPortalCooldown, getPos, getPose, getPosWithYOffset, getRandomBodyY, getRemovalReason, getRenderDistanceMultiplier, getRootVehicle, getRotationClient, getRotationVec, getRotationVecClient, getRotationVector, getRotationVector, getSafeFallDistance, getSavedEntityId, getServer, getStandingEyeHeight, getSteppingBlockState, getSteppingPos, getStepSoundPos, getSwimHeight, getSyncedPos, getTargetingMargin, getTeamColorValue, getTrackedPosition, getType, getUuid, getUuidAsString, getVehicle, getVelocity, getVelocityAffectingPos, getWidth, getWorld, getX, getY, getYaw, getZ, handleAttack, hasCollidedSoftly, hasControllingPassenger, hasCustomName, hashCode, hasNoGravity, hasPassenger, hasPassenger, hasPassengerDeep, hasPassengers, hasPermissionLevel, hasPlayerRider, hasPortalCooldown, hasVehicle, interact, interactAt, isAttackable, isCollidable, isConnectedThroughVehicle, isCrawling, isCustomNameVisible, isDescending, isFireImmune, isFlappingWings, isFrozen, isGlowingLocal, isImmuneToExplosion, isInLava, isInPose, isInRange, isInRange, isInsideWaterOrBubbleColumn, isInSneakingPose, isInvisible, isInvisibleTo, isInvulnerable, isLiving, isLogicalSideForUpdatingMovement, isOnFire, isOnGround, isOnRail, isPartOf, isRegionUnloaded, isRemoved, isSilent, isSneaking, isSneaky, isSprinting, isSubmergedIn, isSubmergedInWater, isSupportedBy, isTeammate, isTeamPlayer, isTouchingWater, isTouchingWaterOrRain, isWet, limitFallDistance, move, occludeVibrationSignals, offsetX, offsetZ, onBubbleColumnCollision, onBubbleColumnSurfaceCollision, onDataTrackerUpdate, onPassengerLookAround, onPlayerCollision, onRemoved, onStartedTrackingBy, onStoppedTrackingBy, onStruckByLightning, playCombinationStepSounds, playExtinguishSound, playSecondaryStepSound, playSoundIfNotSilent, playSwimSound, playSwimSound, populateCrashReport, pushOutOfBlocks, raycast, readNbt, refreshPosition, refreshPositionAfterTeleport, refreshPositionAndAngles, refreshPositionAndAngles, reinitDimensions, removeAllPassengers, removeFromDimension, removePassenger, removeScoreboardTag, resetPortalCooldown, resetPosition, saveNbt, saveSelfNbt, scheduleVelocityUpdate, setAir, setBoundingBox, setChangeListener, setCustomName, setCustomNameVisible, setFlag, setFrozenTicks, setGlowing, setId, setInNetherPortal, setInPowderSnow, setInvisible, setInvulnerable, setNoGravity, setOnFire, setOnFireFor, setOnFireFromLava, setOnGround, setOnGround, setPitch, setPortalCooldown, setPos, setPose, setPosition, setPosition, setRemoved, setRenderDistanceMultiplier, setRotation, setSilent, setSneaking, setStepHeight, setSwimming, setUuid, setVelocity, setVelocity, setVelocityClient, setWorld, setYaw, shouldBroadcastConsoleToOps, shouldDismountUnderwater, shouldEscapePowderSnow, shouldReceiveFeedback, shouldRender, shouldRender, shouldSetPositionOnLoad, shouldSpawnSprintingParticles, shouldTrackOutput, spawnSprintingParticles, squaredDistanceTo, squaredDistanceTo, squaredDistanceTo, startRiding, streamPassengersAndSelf, streamSelfAndPassengers, teleport, tickPortal, toNbtList, toNbtList, toString, tryCheckBlockCollision, unsetRemoved, updateEventHandler, updateMovementInFluid, updatePassengerForDismount, updatePassengerPosition, updatePassengerPosition, updatePosition, updatePositionAndAngles, updateSupportingBlockPos, updateTrackedPosition, updateVelocity, updateWaterState, wouldPoseNotCollide, writeNbt
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
Methods inherited from interface net.minecraft.server.command.CommandOutput
cannotBeSilenced
-
Field Details
-
DEFAULT_UUID
Default UUID, for fake players not associated with a specific (human) player.
-
-
Constructor Details
-
FakePlayer
-
-
Method Details
-
get
Retrieves a fake player for the specified world, using thedefault UUID
. This is suitable when the fake player is not associated with a specific (human) player. Otherwise, the UUID of the owning (human) player should be used (see class javadoc).Instances are reused for the same world parameter.
Caution should be exerted when storing the returned value, as strong references to the fake player will keep the world loaded.
-
get
Retrieves a fake player for the specified world and game profile. See class javadoc for more information on fake player game profiles.Instances are reused for the same parameters.
Caution should be exerted when storing the returned value, as strong references to the fake player will keep the world loaded.
-
tick
public void tick()- Overrides:
tick
in classServerPlayerEntity
-
setClientSettings
- Overrides:
setClientSettings
in classServerPlayerEntity
-
increaseStat
- Overrides:
increaseStat
in classServerPlayerEntity
-
resetStat
- Overrides:
resetStat
in classServerPlayerEntity
-
isInvulnerableTo
- Overrides:
isInvulnerableTo
in classServerPlayerEntity
-
getScoreboardTeam
- Overrides:
getScoreboardTeam
in classEntity
-
sleep
- Overrides:
sleep
in classServerPlayerEntity
-
startRiding
- Overrides:
startRiding
in classServerPlayerEntity
-
openEditSignScreen
- Overrides:
openEditSignScreen
in classServerPlayerEntity
-
openHandledScreen
- Overrides:
openHandledScreen
in classServerPlayerEntity
-
openHorseInventory
- Overrides:
openHorseInventory
in classServerPlayerEntity
-