Make player face front of chest

Discussion in 'Spigot Plugin Development' started by NegativeExpert9, Jan 9, 2020.

  1. hey there,

    recently i've been trying to get a player to teleport to a chest facing it.

    so my question is, how would I get the direction a chest is facing (is it something to do with Block#getData).
    and then, how would i teleport a player to a location facing the OPPOSITE of that location.

    thanks a lot!
  2. get the direction (assuming you know the block or its location and can be sure it's a chest):

    Code (Java):
    final Block chest = ... // whatever way you wanna get chest
    final Directional chestData = (Directional) block.getBlockData();
    final BlockFace face = chestData.getFacing();
    You then want to compute the new teleport location, taking into account the yaw (the direction the player is facing)

    Code (Java):
    final Location location = chest.getLocation();
    final double distance = 1.0;
    switch (face) {
       case NORTH:
       case SOUTH:
           int modZ = face.getModZ();
           location.setYaw(modZ < 0 ? 0F : 180F);
           location.add(0.5, 0, modZ < 0 ? - distance : (distance + 1));
       case EAST:
       case WEST:
           int modX = face.getModX();
           location.setYaw(modX < 0 ? - 90F : 90F);
           location.add(modX < 0 ? - distance: (distance + 1), 0, 0.5);
    Alternatively, you could compute the middle point and use some smart maths to compute the position of the player

    If you want the player to look down to the chest, set his pitch as well (to about 45 or calculate it using trigonometry if you want to take into account the distance)
    If you want the player to be a bit further away than one block, set the distance accordingly.

    Finally, you can teleport the player

    Code (Java):
    Note that this only works for single chests. For double chests, you should be able to adapt the numbers if you understand what this does
    • Friendly Friendly x 1
  3. thanks alot, this makes sense