How to get Player Position Change Amount

Discussion in 'Plugin Development' started by EinsMalte, Apr 7, 2021.

Thread Status:
Not open for further replies.
  1. Offline

    EinsMalte

    Hey, I wrote a plugin, to find out if a player moves and the angle at which it moves. But the problem is, the amount the player moved is either 1 or 0 which doesnt work out. Could somebody help me in finding out, how to get a float value of how much the player moved?

    Code:
    @EventHandler
        public void onMove(PlayerMoveEvent e) {
            Player p = e.getPlayer();
            float direction = (float) Math.toRadians(p.getLocation().getYaw());
           
            float new_x = e.getTo().getBlockX();
            float old_x = e.getFrom().getBlockX();
           
            float new_y = e.getTo().getBlockY();
            float old_y = e.getFrom().getBlockY();
           
            float moved_x = new_x-old_x;
            float moved_y = new_y-old_y;
           
            if(moved_x != 0 || moved_y != 0)  {
            float distance = (float) Math.sqrt(((moved_x)*(moved_x)+(moved_y)*(moved_y)));
           
           
            float moved_direction = (float) Math.asin(moved_x/distance);
            //console.sendMessage("Player joined and facing");
            //console.sendMessage(direction + "");
            e.getPlayer().sendMessage("You moved: X" + moved_x + " Y:" + moved_y + " Dist:" + distance + "Facing:" + direction + "Going:" + moved_direction);
            }
            return;
           
        }
     
  2. Offline

    KarimAKL

    @EinsMalte Bukkit has utility methods for this, so you need not type it yourself.

    You can get the distance with this:
    Code:Java
    1. @EventHandler
    2. public void onMove(PlayerMoveEvent event) {
    3. double distance = event.getTo().distance(event.getFrom());
    4.  
    5. event.getPlayer("Distance: " + distance + " blocks");
    6. }


    The direction can be gotten as a vector by subtracting the two vectors:
    Code:Java
    1. @EventHandler
    2. public void onMove(PlayerMoveEvent event) {
    3. Vector direction = event.getTo().toVector().substract(event.getFrom().toVector());
    4.  
    5. event.getPlayer("Direction: " + direction);
    6. }
     
  3. Offline

    EinsMalte

    Thanks, it works great, but can you please tell me, how I can get the players head Y rotation out of these values? I want to compare the moving direction to the actual head rotation.
     
Thread Status:
Not open for further replies.

Share This Page