Class Entity

java.lang.Object
net.minestom.server.entity.Entity
All Implemented Interfaces:
Sound.Emitter, HoverEventSource<HoverEvent.ShowEntity>, EventHandler<EntityEvent>, PermissionHandler, Snapshotable, Taggable, TagReadable, TagWritable, Tickable, Schedulable, Viewable
Direct Known Subclasses:
EntityProjectile, ExperienceOrb, ItemEntity, LivingEntity

Could be a player, a monster, or an object.

To create your own entity you probably want to extends LivingEntity or EntityCreature instead.

  • Field Details

    • instance

      protected Instance instance
    • currentChunk

      protected Chunk currentChunk
    • position

      protected Pos position
    • previousPosition

      protected Pos previousPosition
    • lastSyncedPosition

      protected Pos lastSyncedPosition
    • onGround

      protected boolean onGround
    • vehicle

      protected Entity vehicle
    • velocity

      protected Vec velocity
    • lastVelocityWasZero

      protected boolean lastVelocityWasZero
    • hasPhysics

      protected boolean hasPhysics
    • gravityDragPerTick

      protected double gravityDragPerTick
      The amount of drag applied on the Y axle.

      Unit: 1/tick

    • gravityAcceleration

      protected double gravityAcceleration
      Acceleration on the Y axle due to gravity

      Unit: blocks/tick

    • gravityTickCount

      protected int gravityTickCount
    • trackingUpdate

      protected final EntityTracker.Update<Entity> trackingUpdate
    • viewEngine

      protected final net.minestom.server.entity.EntityView viewEngine
    • viewers

      protected final Set<Player> viewers
    • uuid

      protected UUID uuid
    • entityType

      protected EntityType entityType
    • metadata

      protected Metadata metadata
    • entityMeta

      protected EntityMeta entityMeta
  • Constructor Details

    • Entity

      public Entity(@NotNull @NotNull EntityType entityType, @NotNull @NotNull UUID uuid)
    • Entity

      public Entity(@NotNull @NotNull EntityType entityType)
  • Method Details

    • scheduleNextTick

      public void scheduleNextTick(@NotNull @NotNull Consumer<Entity> callback)
      Schedules a task to be run during the next entity tick.
      Parameters:
      callback - the task to execute during the next entity tick
    • getEntity

      @Nullable public static @Nullable Entity getEntity(int id)
      Gets an entity based on its id (from getEntityId()).

      Entity id are unique server-wide.

      Parameters:
      id - the entity unique id
      Returns:
      the entity having the specified id, null if not found
    • getEntity

      @Nullable public static @Nullable Entity getEntity(@NotNull @NotNull UUID uuid)
      Gets an entity based on its UUID (from getUuid()).
      Parameters:
      uuid - the entity UUID
      Returns:
      the entity having the specified uuid, null if not found
    • generateId

      public static int generateId()
      Generate and return a new unique entity id.

      Useful if you want to spawn entities using packet but don't risk to have duplicated id.

      Returns:
      a newly generated entity id
    • update

      public void update(long time)
      Called each tick.
      Parameters:
      time - time of the update in milliseconds
    • spawn

      public void spawn()
      Called when a new instance is set.
    • isOnGround

      public boolean isOnGround()
    • getEntityMeta

      @NotNull public @NotNull EntityMeta getEntityMeta()
      Gets metadata of this entity. You may want to cast it to specific implementation.
      Returns:
      metadata of this entity.
    • teleport

      @NotNull public @NotNull CompletableFuture<Void> teleport(@NotNull @NotNull Pos position, long @Nullable [] chunks)
      Teleports the entity only if the chunk at position is loaded or if Instance.hasEnabledAutoChunkLoad() returns true.
      Parameters:
      position - the teleport position
      chunks - the chunk indexes to load before teleporting the entity, indexes are from ChunkUtils.getChunkIndex(int, int), can be null or empty to only load the chunk at position
      Throws:
      IllegalStateException - if you try to teleport an entity before settings its instance
    • teleport

      @NotNull public @NotNull CompletableFuture<Void> teleport(@NotNull @NotNull Pos position)
    • setView

      public void setView(float yaw, float pitch)
      Changes the view of the entity.
      Parameters:
      yaw - the new yaw
      pitch - the new pitch
    • lookAt

      public void lookAt(@NotNull @NotNull Point point)
      Changes the view of the entity so that it looks in a direction to the given position if it is different from the entity's current position.
      Parameters:
      point - the point to look at.
    • lookAt

      public void lookAt(@NotNull @NotNull Entity entity)
      Changes the view of the entity so that it looks in a direction to the given entity.
      Parameters:
      entity - the entity to look at.
      Throws:
      IllegalArgumentException - if the entities are not in the same instance
    • isAutoViewable

      public boolean isAutoViewable()
      Gets if this entity is automatically sent to surrounding players. True by default.
      Returns:
      true if the entity is automatically viewable for close players, false otherwise
    • setAutoViewable

      public void setAutoViewable(boolean autoViewable)
      Decides if this entity should be auto-viewable by nearby players.
      Parameters:
      autoViewable - true to add surrounding players, false to remove
      See Also:
    • updateViewableRule

      @Experimental public void updateViewableRule(@Nullable @Nullable Predicate<Player> predicate)
    • updateViewableRule

      @Experimental public void updateViewableRule()
    • autoViewEntities

      @Experimental public boolean autoViewEntities()
      Gets if surrounding entities are automatically visible by this. True by default.
      Returns:
      true if surrounding entities are visible by this
    • setAutoViewEntities

      @Experimental public void setAutoViewEntities(boolean autoViewer)
      Decides if surrounding entities must be visible.
      Parameters:
      autoViewer - true to add view surrounding entities, false to remove
    • updateViewerRule

      @Experimental public void updateViewerRule(@Nullable @Nullable Predicate<Entity> predicate)
    • updateViewerRule

      @Experimental public void updateViewerRule()
    • addViewer

      public final boolean addViewer(@NotNull @NotNull Player player)
      Description copied from interface: Viewable
      Adds a viewer.
      Specified by:
      addViewer in interface Viewable
      Parameters:
      player - the viewer to add
      Returns:
      true if the player has been added, false otherwise (could be because he is already a viewer)
    • removeViewer

      public final boolean removeViewer(@NotNull @NotNull Player player)
      Description copied from interface: Viewable
      Removes a viewer.
      Specified by:
      removeViewer in interface Viewable
      Parameters:
      player - the viewer to remove
      Returns:
      true if the player has been removed, false otherwise (could be because he was not a viewer)
    • updateNewViewer

      @Internal public void updateNewViewer(@NotNull @NotNull Player player)
      Called when a new viewer must be shown. Method can be subject to deadlocking if the target's viewers are also accessed.
      Parameters:
      player - the player to send the packets to
    • updateOldViewer

      @Internal public void updateOldViewer(@NotNull @NotNull Player player)
      Called when a viewer must be destroyed. Method can be subject to deadlocking if the target's viewers are also accessed.
      Parameters:
      player - the player to send the packets to
    • getViewers

      @NotNull public @NotNull Set<Player> getViewers()
      Description copied from interface: Viewable
      Gets all the viewers of this viewable element.
      Specified by:
      getViewers in interface Viewable
      Returns:
      A Set containing all the element's viewers
    • hasPredictableViewers

      public boolean hasPredictableViewers()
      Gets if this entity's viewers (surrounding players) can be predicted from surrounding chunks.
    • switchEntityType

      public void switchEntityType(@NotNull @NotNull EntityType entityType)
      Changes the entity type of this entity.

      Works by changing the internal entity type field and by calling removeViewer(Player) followed by addViewer(Player) to all current viewers.

      Be aware that this only change the visual of the entity, the BoundingBox will not be modified.

      Parameters:
      entityType - the new entity type
    • getAllPermissions

      @NotNull public @NotNull Set<Permission> getAllPermissions()
      Description copied from interface: PermissionHandler
      Returns all permissions associated to this handler. The returned collection should be modified only by subclasses.
      Specified by:
      getAllPermissions in interface PermissionHandler
      Returns:
      the permissions of this handler.
    • tick

      public void tick(long time)
      Updates the entity, called every tick.

      Ignored if getInstance() returns null.

      Specified by:
      tick in interface Tickable
      Parameters:
      time - the update time in milliseconds
    • updateVelocity

      protected void updateVelocity(boolean wasOnGround, boolean flying, Pos positionBeforeMove, Vec newVelocity)
    • getAliveTicks

      public long getAliveTicks()
      Gets the number of ticks this entity has been active for.
      Returns:
      the number of ticks this entity has been active for
    • handleVoid

      protected void handleVoid()
      How does this entity handle being in the void?
    • getEntityId

      public int getEntityId()
      Each entity has an unique id (server-wide) which will change after a restart.
      Returns:
      the unique entity id
      See Also:
    • getEntityType

      @NotNull public @NotNull EntityType getEntityType()
      Returns the entity type.
      Returns:
      the entity type
    • getUuid

      @NotNull public @NotNull UUID getUuid()
      Gets the entity UUID.
      Returns:
      the entity unique id
    • setUuid

      public void setUuid(@NotNull @NotNull UUID uuid)
      Changes the internal entity UUID, mostly unsafe.
      Parameters:
      uuid - the new entity uuid
    • isActive

      public boolean isActive()
      Returns false just after instantiation, set to true after calling setInstance(Instance).
      Returns:
      true if the entity has been linked to an instance, false otherwise
    • getBoundingBox

      @NotNull public @NotNull BoundingBox getBoundingBox()
      Returns the current bounding box (based on pose). Is used to check collision with coordinates or other blocks/entities.
      Returns:
      the entity bounding box
    • setBoundingBox

      public void setBoundingBox(double width, double height, double depth)
      Changes the internal entity standing bounding box. When the pose is not standing, a different bounding box may be used for collision.

      WARNING: this does not change the entity hit-box which is client-side.

      Parameters:
      width - the bounding box X size
      height - the bounding box Y size
      depth - the bounding box Z size
    • setBoundingBox

      public void setBoundingBox(BoundingBox boundingBox)
      Changes the internal entity standing bounding box. When the pose is not standing, a different bounding box may be used for collision.

      WARNING: this does not change the entity hit-box which is client-side.

      Parameters:
      boundingBox - the new bounding box
    • getChunk

      @Nullable public @Nullable Chunk getChunk()
      Convenient method to get the entity current chunk.
      Returns:
      the entity chunk, can be null even if unlikely
    • refreshCurrentChunk

      @Internal protected void refreshCurrentChunk(Chunk currentChunk)
    • getInstance

      @Nullable public @Nullable Instance getInstance()
      Gets the entity current instance.
      Returns:
      the entity instance, can be null if the entity doesn't have an instance yet
    • setInstance

      public CompletableFuture<Void> setInstance(@NotNull @NotNull Instance instance, @NotNull @NotNull Pos spawnPosition)
      Changes the entity instance, i.e. spawns it.
      Parameters:
      instance - the new instance of the entity
      spawnPosition - the spawn position for the entity.
      Returns:
      a CompletableFuture called once the entity's instance has been set, this is due to chunks needing to load
      Throws:
      IllegalStateException - if instance has not been registered in InstanceManager
    • setInstance

      public CompletableFuture<Void> setInstance(@NotNull @NotNull Instance instance, @NotNull @NotNull Point spawnPosition)
    • setInstance

      public CompletableFuture<Void> setInstance(@NotNull @NotNull Instance instance)
      Changes the entity instance.
      Parameters:
      instance - the new instance of the entity
      Returns:
      a CompletableFuture called once the entity's instance has been set, this is due to chunks needing to load
      Throws:
      NullPointerException - if instance is null
      IllegalStateException - if instance has not been registered in InstanceManager
    • getVelocity

      @NotNull public @NotNull Vec getVelocity()
      Gets the entity current velocity.
      Returns:
      the entity current velocity
    • setVelocity

      public void setVelocity(@NotNull @NotNull Vec velocity)
      Changes the entity velocity and calls EntityVelocityEvent.

      The final velocity can be cancelled or modified by the event.

      Parameters:
      velocity - the new entity velocity
    • hasVelocity

      public boolean hasVelocity()
      Gets if the entity currently has a velocity applied.
      Returns:
      true if the entity is moving
    • getGravityDragPerTick

      public double getGravityDragPerTick()
      Gets the gravity drag per tick.
      Returns:
      the gravity drag per tick in block
    • getGravityAcceleration

      public double getGravityAcceleration()
      Gets the gravity acceleration.
      Returns:
      the gravity acceleration in block
    • getGravityTickCount

      public int getGravityTickCount()
      Gets the number of tick this entity has been applied gravity.
      Returns:
      the number of tick of which gravity has been consequently applied
    • setGravity

      public void setGravity(double gravityDragPerTick, double gravityAcceleration)
      Changes the gravity of the entity.
      Parameters:
      gravityDragPerTick - the gravity drag per tick in block
      gravityAcceleration - the gravity acceleration in block
      See Also:
    • getDistance

      public double getDistance(@NotNull @NotNull Point point)
    • getDistance

      public double getDistance(@NotNull @NotNull Entity entity)
      Gets the distance between two entities.
      Parameters:
      entity - the entity to get the distance from
      Returns:
      the distance between this and entity
    • getDistanceSquared

      public double getDistanceSquared(@NotNull @NotNull Entity entity)
      Gets the distance squared between two entities.
      Parameters:
      entity - the entity to get the distance from
      Returns:
      the distance squared between this and entity
    • getVehicle

      @Nullable public @Nullable Entity getVehicle()
      Gets the entity vehicle or null.
      Returns:
      the entity vehicle, or null if there is not any
    • addPassenger

      public void addPassenger(@NotNull @NotNull Entity entity)
      Adds a new passenger to this entity.
      Parameters:
      entity - the new passenger
      Throws:
      NullPointerException - if entity is null
      IllegalStateException - if getInstance() returns null or the passenger cannot be added
    • removePassenger

      public void removePassenger(@NotNull @NotNull Entity entity)
      Removes a passenger to this entity.
      Parameters:
      entity - the passenger to remove
      Throws:
      NullPointerException - if entity is null
      IllegalStateException - if getInstance() returns null
    • hasPassenger

      public boolean hasPassenger()
      Gets if the entity has any passenger.
      Returns:
      true if the entity has any passenger, false otherwise
    • getPassengers

      @NotNull public @NotNull Set<@NotNull Entity> getPassengers()
      Gets the entity passengers.
      Returns:
      an unmodifiable list containing all the entity passengers
    • getPassengersPacket

      @NotNull protected @NotNull SetPassengersPacket getPassengersPacket()
    • triggerStatus

      public void triggerStatus(byte status)
      Entity statuses can be found here.
      Parameters:
      status - the status to trigger
    • isOnFire

      public boolean isOnFire()
      Gets if the entity is on fire.
      Returns:
      true if the entity is in fire, false otherwise
    • setOnFire

      public void setOnFire(boolean fire)
      Sets the entity in fire visually.

      WARNING: if you want to apply damage or specify a duration, see LivingEntity.setFireForDuration(int, TemporalUnit).

      Parameters:
      fire - should the entity be set in fire
    • isSneaking

      public boolean isSneaking()
      Gets if the entity is sneaking.

      WARNING: this can be bypassed by hacked client, this is only what the client told the server.

      Returns:
      true if the player is sneaking
    • setSneaking

      public void setSneaking(boolean sneaking)
      Makes the entity sneak.

      WARNING: this will not work for the client itself.

      Parameters:
      sneaking - true to make the entity sneak
    • isSprinting

      public boolean isSprinting()
      Gets if the player is sprinting.

      WARNING: this can be bypassed by hacked client, this is only what the client told the server.

      Returns:
      true if the player is sprinting
    • setSprinting

      public void setSprinting(boolean sprinting)
      Makes the entity sprint.

      WARNING: this will not work on the client itself.

      Parameters:
      sprinting - true to make the entity sprint
    • isInvisible

      public boolean isInvisible()
      Gets if the entity is invisible or not.
      Returns:
      true if the entity is invisible, false otherwise
    • setInvisible

      public void setInvisible(boolean invisible)
      Changes the internal invisible value and send a EntityMetaDataPacket to make visible or invisible the entity to its viewers.
      Parameters:
      invisible - true to set the entity invisible, false otherwise
    • isGlowing

      public boolean isGlowing()
      Gets if the entity is glowing or not.
      Returns:
      true if the entity is glowing, false otherwise
    • setGlowing

      public void setGlowing(boolean glowing)
      Sets or remove the entity glowing effect.
      Parameters:
      glowing - true to make the entity glows, false otherwise
    • getPose

      @NotNull public @NotNull Entity.Pose getPose()
      Gets the current entity pose.
      Returns:
      the entity pose
    • setPose

      public void setPose(@NotNull @NotNull Entity.Pose pose)
      Changes the entity pose.

      The internal crouched and swimming field will be updated accordingly.

      Parameters:
      pose - the new entity pose
    • updatePose

      protected void updatePose()
    • getCustomName

      @Nullable public @Nullable Component getCustomName()
      Gets the entity custom name.
      Returns:
      the custom name of the entity, null if there is not
    • setCustomName

      public void setCustomName(@Nullable @Nullable Component customName)
      Changes the entity custom name.
      Parameters:
      customName - the custom name of the entity, null to remove it
    • isCustomNameVisible

      public boolean isCustomNameVisible()
      Gets the custom name visible metadata field.
      Returns:
      true if the custom name is visible, false otherwise
    • setCustomNameVisible

      public void setCustomNameVisible(boolean customNameVisible)
      Changes the internal custom name visible field and send a EntityMetaDataPacket to update the entity state to its viewers.
      Parameters:
      customNameVisible - true to make the custom name visible, false otherwise
    • isSilent

      public boolean isSilent()
    • setSilent

      public void setSilent(boolean silent)
    • hasNoGravity

      public boolean hasNoGravity()
      Gets the noGravity metadata field.
      Returns:
      true if the entity ignore gravity, false otherwise
    • setNoGravity

      public void setNoGravity(boolean noGravity)
      Changes the noGravity metadata field and change the gravity behaviour accordingly.
      Parameters:
      noGravity - should the entity ignore gravity
    • refreshPosition

      @Internal public void refreshPosition(@NotNull @NotNull Pos newPosition, boolean ignoreView)
      Updates internal fields and sends updates.
      Parameters:
      newPosition - the new position
    • refreshPosition

      @Internal public void refreshPosition(@NotNull @NotNull Pos newPosition)
    • getPosition

      @NotNull public @NotNull Pos getPosition()
      Gets the entity position.
      Returns:
      the current position of the entity
    • getEyeHeight

      public double getEyeHeight()
      Gets the entity eye height.

      Default to BoundingBox.height()x0.85

      Returns:
      the entity eye height
    • getActiveEffects

      @NotNull public @NotNull List<@NotNull TimedPotion> getActiveEffects()
      Gets all the potion effect of this entity.
      Returns:
      an unmodifiable list of all this entity effects
    • addEffect

      public void addEffect(@NotNull @NotNull Potion potion)
      Adds an effect to an entity.
      Parameters:
      potion - The potion to add
    • removeEffect

      public void removeEffect(@NotNull @NotNull PotionEffect effect)
      Removes effect from entity, if it has it.
      Parameters:
      effect - The effect to remove
    • clearEffects

      public void clearEffects()
      Removes all the effects currently applied to the entity.
    • remove

      public void remove()
      Removes the entity from the server immediately.

      WARNING: this does not trigger EntityDeathEvent.

    • isRemoved

      public boolean isRemoved()
      Gets if this entity has been removed.
      Returns:
      true if this entity is removed
    • scheduleRemove

      public void scheduleRemove(long delay, @NotNull @NotNull TemporalUnit temporalUnit)
      Triggers remove() after the specified time.
      Parameters:
      delay - the time before removing the entity, 0 to cancel the removing
      temporalUnit - the unit of the delay
    • scheduleRemove

      public void scheduleRemove(Duration delay)
      Triggers remove() after the specified time.
      Parameters:
      delay - the time before removing the entity
    • getVelocityForPacket

      @NotNull protected @NotNull Vec getVelocityForPacket()
    • getVelocityPacket

      @NotNull protected @NotNull EntityVelocityPacket getVelocityPacket()
    • getMetadataPacket

      @NotNull public @NotNull EntityMetaDataPacket getMetadataPacket()
      Gets an EntityMetaDataPacket sent when adding viewers. Used for synchronization.
      Returns:
      The EntityMetaDataPacket related to this entity
    • synchronizePosition

      @Internal protected void synchronizePosition(boolean includeSelf)
      Used to synchronize entity position with viewers by sending an EntityTeleportPacket to viewers, in case of a player this is overridden in order to send an additional PlayerPositionAndLookPacket to itself.
      Parameters:
      includeSelf - if true and this is a Player an additional PlayerPositionAndLookPacket will be sent to the player itself
    • askSynchronization

      public void askSynchronization()
      Asks for a synchronization (position) to happen during next entity tick.
    • setCustomSynchronizationCooldown

      public void setCustomSynchronizationCooldown(@Nullable @Nullable Duration cooldown)
      Set custom cooldown for position synchronization.
      Parameters:
      cooldown - custom cooldown for position synchronization.
    • asHoverEvent

      @NotNull public @NotNull HoverEvent<HoverEvent.ShowEntity> asHoverEvent(@NotNull @NotNull UnaryOperator<HoverEvent.ShowEntity> op)
      Specified by:
      asHoverEvent in interface HoverEventSource<HoverEvent.ShowEntity>
    • getAcquirable

      @Experimental @NotNull public <T extends Entity> @NotNull Acquirable<T> getAcquirable()
    • tagHandler

      @NotNull public @NotNull TagHandler tagHandler()
      Specified by:
      tagHandler in interface Taggable
    • scheduler

      @NotNull public @NotNull Scheduler scheduler()
      Specified by:
      scheduler in interface Schedulable
    • updateSnapshot

      @NotNull public @NotNull EntitySnapshot updateSnapshot(@NotNull @NotNull SnapshotUpdater updater)
      Description copied from interface: Snapshotable
      Updates the currently cached snapshot if required. The updater can be used to retrieve references to other snapshots while avoiding circular dependency. Be careful to do not store updater anywhere as its data will change when building requested references.

      This method is not thread-safe, and targeted at internal use since its execution rely on safe-points (e.g. end of ticks)

      Specified by:
      updateSnapshot in interface Snapshotable
      Parameters:
      updater - the snapshot updater/context
      Returns:
      the updated snapshot
    • eventNode

      @Experimental @NotNull public @NotNull EventNode<EntityEvent> eventNode()
      Specified by:
      eventNode in interface EventHandler<EntityEvent>
    • takeKnockback

      public void takeKnockback(float strength, double x, double z)
      Applies knockback to the entity
      Parameters:
      strength - the strength of the knockback, 0.4 is the vanilla value for a bare hand hit
      x - knockback on x axle, for default knockback use the following formula
      sin(attacker.yaw * (pi/180))
      z - knockback on z axle, for default knockback use the following formula
      -cos(attacker.yaw * (pi/180))
    • getLineOfSight

      public List<Point> getLineOfSight(int maxDistance)
      Gets the line of sight of the entity.
      Parameters:
      maxDistance - The max distance to scan
      Returns:
      A list of points in this entities line of sight
    • hasLineOfSight

      public boolean hasLineOfSight(Entity entity, boolean exactView)
      Raycasts current entity's eye position to target eye position.
      Parameters:
      entity - the entity to be checked.
      exactView - if set to TRUE, checks whether target is IN the line of sight of the current one; otherwise checks if the current entity can rotate so that target will be in its line of sight.
      Returns:
      true if the ray reaches the target bounding box before hitting a block.
    • hasLineOfSight

      public boolean hasLineOfSight(Entity entity)
      Parameters:
      entity - the entity to be checked.
      Returns:
      if the current entity has line of sight to the given one.
      See Also:
    • getLineOfSightEntity

      @Nullable public @Nullable Entity getLineOfSightEntity(double range, Predicate<Entity> predicate)
      Gets first entity on the line of sight of the current one that matches the given predicate.
      Parameters:
      range - max length of the line of sight of the current entity to be checked.
      predicate - optional predicate
      Returns:
      resulting entity whether there're any, null otherwise.