javaminecraftbukkit

Get the direction a Player is looking?


I tried to get the direction, like North, South, West, East, of a Players Facing. I created this code, but sometimes it doesn't work...

package me.Nightfighter001.GlobalSystem.WorldEditor;

import org.bukkit.entity.Player;

public enum Yaw {
    NORTH, SOUTH, EAST, WEST;

    public static Yaw getYaw(Player p) {
        float yaw = p.getLocation().getYaw();
        if (yaw > 135 || yaw < -135) {
            return Yaw.NORTH;
        } else if (yaw < -45) {
            return Yaw.EAST;
        } else if (yaw > 45) {
            return Yaw.WEST;
        } else {
            return Yaw.SOUTH;
        }
    }
}

Can someone help me, please? Sorry for my bad English and thank you :)


Solution

  • The answer that was marked as correct works, but in theory the yaw can also have values above 360 degrees (noted in the documentation), so just handling negative values might cause bugs at some point.

    The code here is your exact code, but it uses a true modulo implementation to get the angle in the 0-360 degree range.

    public static Yaw getYaw(Player p) {
        float yaw = p.getLocation().getYaw();
        yaw = (yaw % 360 + 360) % 360; // true modulo, as javas modulo is weird for negative values
        if (yaw > 135 || yaw < -135) {
            return Yaw.NORTH;
        } else if (yaw < -45) {
            return Yaw.EAST;
        } else if (yaw > 45) {
            return Yaw.WEST;
        } else {
            return Yaw.SOUTH;
        }
    }