Jump to content

how to filter: walking to npcs only when players arent near them


Recommended Posts

Posted

Using filters!

 

Two ways:

 

 

1.

        getNpcs().filter(new Filter<NPC>() {
            @[member='Override']
            public boolean match(NPC obj) {
                return obj.getPosition().distance(myPosition()) > 2;
            }
        });
        

 

2.

        java.util.List<NPC> npcs = getNpcs().getAll().stream().filter(n -> n.getPosition().distance(myPosition()) > 2).collect(Collectors.toList())
       
 

 

Edit:

Then you can use a comparator:

        npcs.sort(new Comparator<NPC>() {
            public int compare(NPC npc1, NPC npc2) {
                return npc1.getPosition().distance(myPosition()) - npc2.getPosition().distance(myPosition());
            }
        });

So this will return the closest npc which is more than 2 tiles away.

  • Like 2
Posted (edited)

Hello :) I was just wondering how i would implement a filter to get the closest npc of a certain type but to make sure it is not ~2 squares away from the npc so that im not crashing someone else's spot as that would look quite botty.

Optional<NPC> npcOpt = getNpcs().getAll()
                        .stream()
                        .filter(n -> n.getName().equals("NPC Name") &&
                                     n.getPosition().distance(myPosition()) > 2)
                        .min((n1, n2) -> Integer.compare(n1.getPosition().distance(myPosition()),
                                                       ​n2.getPosition().distance(myPosition())));

Explanation:

 

  1. Construct a Stream<NPC> of all the NPCs around the Player
  2. Filter the Stream<NPC> so that only the NPCs who's name matches "NPC Name" and is more than two tiles away from the player remain
  3. Apply the min function to the Stream<NPC> using a custom comparator that compares distances from the player (essentially returns the closest NPC to the player)
  4. Returns an Optional<NPC>

 

With the return value of Optional<NPC>, instead of null checking you do something like:

npcOpt.ifPresent(npc -> {

});

For more information on the Optional class see https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

 

For more information on streams see http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html and https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html

Edited by Explv

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...