I'm creating a plugin for an event, this event is just: when you stop moving, you loose. I created everything, but my check to know if a player moves or not doesn't work:
I tried to make an array and when a player move event it's added, but it doesn't work,
@EventHandler
public static void OnPlayerMoov(PlayerMoveEvent e) {
if(!playerHaveMooved.contains(e.getPlayer())) {
playerHaveMooved.add(e.getPlayer());
}
}
public static boolean isMoving(Player p){
System.out.println(Respawn.playerHaveMooved.contains(p));
return Respawn.playerHaveMooved.contains(p);
}
I tried to use velocity; it doesn't work,
public static boolean isMoving(Player p){
return (p.getVelocity().length() == 0);
}
It doesn't work. It kills me when I am moving.
Do you have a solution?
CodePudding user response:
The first don't work because you just check if the player already move a time, which will always be true.
The second about velocity check only if player get knockbacked for example.
First solution
Save last time of move, and check each few time if it stop move.
In this example, I will force player to move each seconds.
private final HashMap<Player, Long> timeMove = new HashMap<>(); // map for data
@Eventhandler
public void onMove(PlayerMoveEvent e) {
timeMove.put(e.getPlayer(), System.currentTimeMillis()); // update last move
}
public void startChecking(JavaPlugin pl) {
pl.getServer().getScheduler().runTaskTimer(pl, () -> {
long current = System.currentTimeMillis();
for(Player p : Bukkit.getOnlinePlayers()) {
long last = timeMove.getOrDefault(p, 0);
long diff = current - last;
if(diff > 1000) { // 1000 = second
// player don't move
}
}
}, 20, 20);
}
Second solution
Check each X time from last and current location
private final HashMap<Player, Location> lastLoc = new HashMap<>(); // map for data
public void startChecking(JavaPlugin pl) {
pl.getServer().getScheduler().runTaskTimer(pl, () -> {
for(Player p : Bukkit.getOnlinePlayers()) {
Location lastPlayerLoc = lastLoc.get(p); // get loc, or keep null if not registered
if(lastPlayerLoc != null) {
double distance = lastPlayerLoc.distance(p.getLocation());
if(distance == 0.0) {
// here the player don't move
continue; // go to next player
}
}
lastLoc.put(p, p.getLocation()); // update loc
}
}, 20, 20);
}