Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spigot PlayerInteractEntityEvent

I am using Spigot 1.11.2.

I have this simple code:

@EventHandler
public void onPlayerInteractEntity (PlayerInteractEntityEvent event) {
    if (entity instanceof AbstractHorse) {
        event.setCancelled(true);

        AbstractHorse horse = (AbstractHorse) event.getRightClicked();
        Player player = event.getPlayer();
        player.sendMessage(horse.getName());
    }
}

What it's supposed to do is if I right-click a horse, I should get its name but I shouldn't ride it, because of the event.setCancelled(true). It works as expected, but the problem is that when I right-click a horse, the game turns my view around (my player's yaw) to some number that is not consistent. Yet I don't want to turn around; I still want my player to be looking at where I was looking at (at the horse in this case) after I right-click the horse.

I tried some methods, like saving my pitch and yaw then setting it again after cancelling the event:

@EventHandler
public void onPlayerInteractEntity (PlayerInteractEntityEvent event) {
    Player player = event.getPlayer();
    float pitch = player.getLocation().getPitch();
    float yaw = player.getLocation().getYaw();

    if (entity instanceof AbstractHorse) {
        event.setCancelled(true);
        player.getLocation().setPitch(pitch);
        player.getLocation().setYaw(yaw);

        AbstractHorse horse = (AbstractHorse) event.getRightClicked();
        player.sendMessage(horse.getName());
    }
}

and also similarly tried saving the player's direction (via player.getLocation().getDirection()) then setting it again after cancelling the event, to no avail. Am I doing something wrong here? Or is this a bug?

like image 435
Mark Zedler Avatar asked Apr 10 '26 01:04

Mark Zedler


1 Answers

Well, I found that you can't actually directly edit a player's pitch and yaw. You have to teleport the player to a custom Location with the custom pitch and yaw values, like this:

@EventHandler
public void onPlayerInteractEntity (PlayerInteractEntityEvent event) {
    Entity entity = event.getRightClicked();
    Player player = event.getPlayer();

    float pitch = player.getLocation().getPitch();
    float yaw = player.getLocation().getYaw();

    if (entity instanceof AbstractHorse) {
        event.setCancelled(true);

        Location loc = player.getLocation();
        loc.setPitch(pitch);
        loc.setYaw(yaw);
        player.teleport(loc);

        AbstractHorse horse = (AbstractHorse) event.getRightClicked();
        player.sendMessage(horse.getName());
    }
}

So now the player would still be looking to where they were looking at before right-clicking a horse, although it looks glitchy. There's no other way to do it so far, I believe.

like image 105
Mark Zedler Avatar answered Apr 12 '26 14:04

Mark Zedler