Always checking players position

Hello I was wondering if there was a way to check like every tick if two players are next to each other and if so, do something.
Tried searching for events that could do that but didn’t find anything.
Can anyone help?

Cheers.

@Listener
public void onPlayerMove(MoveEntityEvent evt, @Getter("getTargetEntity") Player player){
    //check positions here
}

You could also create a Task and loop through all players and check if they are near.

The most effective way is the way blue stated. The EntityMoveEvent is fired when a entity moves or teleports. After that check for all players in that players world to see if they are close to the original player (remember to exclude the original player).

There is a example provided by blue for the event. As for detecting distance between two players. You will need to get the vector3d from the target player. After that use a stream to filter all close players.

I think this is not very performance friendly

If you use the squared distance you should be fine … and creating a looping task has roughly the same impact if you want it to have the same reaction-time… (= testing every tick)

But a Task can be run async, so it has no performance impact at all

You should not access most of the api asyncronously…

I think getting locations of Player-Snapshots and comparing them should be fine, but i am really new to Sponge so idk

1 Like

Player snapshots, I belive are part of the SpongeAPI only, as in they are not in NMS. This means you will be fine to access these methods in the async tasks. The problem is when you create the PlayerSnapshots, that i belive will use nms to get all the player data, that part must be in the sync side of things.

You can always try it and if sponge blocks you or minecraft server crashes or something (i dont know what happens when you call a nms method in async). If it works, great, if not you know why.

oh and no one seems to have given you the code for creating tasks in sponge. It is in the sponge docs, however this will get you started.

Sponge.getScheduler().createTaskBuilder().async();

if you want it to continuesly run, then remeber to fill the intival part (the delay is the delay before starting). You can read more about the builder here
https://github.com/SpongePowered/SpongeAPI/blob/bleeding/src/main/java/org/spongepowered/api/scheduler/Task.java

1 Like