1
\$\begingroup\$

I've written a code that allows me to talk with an NPC. This works as long as there is only 1 NPC on the map. I'll explain why.

public void getNPCCollision(){
    for (int i = players.size() - 1; i >= 0; i--) {
        Player player = players.get(i);
        for (int j = beings.size() - 1; j >= 0; j--) {
            Being being = beings.get(j);
            if(player.getBounds().overlaps(being.getBounds())) {
                setX(oldX);
                velocity.x = 0;
                setY(oldY);
                velocity.y = 0;
            }
            else if(player.getBounds().overlaps(being.getTalkingBounds())) {
                canTalk = true;
                talkAbleBeing = being;
            }
            else{
                talkAbleBeing = null;
                canTalk = false;
            }
        }
    }
}

I check every update if my Player walks into an NPC's Talking Rectangle. It goes by every NPC on the map. The thing is If I'm not on NPC 1's rectangle but on NPC 2's rectangle, It'll still set canTalk to False because I'm indeed not in his rectangle.

Is there any way I can fix this issue? Please, any help appreciated.

\$\endgroup\$
4
\$\begingroup\$

If I understood you correctly, instead of defining "canTalk" as a boolean, you can just define it as an integer and start by assigning it either a NULL value or a -1. Then when the player is within the square range of any of the NPC, you just assign the canTalk = NPC index (0,1,2...n where n is total number of NPCs).

Then, you set the dialogue function to run not when canTalk is equal to true, but when it is greater than -1 or different from NULL. Inside the call function, you can even use the canTalk values to define which dialogue will be displayed. For instance, if canTalk = 3, display the dialogue related to NPC 3, if canTalk = 15, display the dialogue related to NPC 15, etc.

This way you can solve your problem and also win for free an easier way to identify which dialogue to display.

\$\endgroup\$
1
\$\begingroup\$

If I understand you correctly...and you only want to be able to talk to one NPC at a time: once you overlap an NPC's talking rectangle, you could break away from the for loops, thus leaving the variables as they were, not allowing another NPC who is not within range to reset the variables to False. For instance:

else if(player.getBounds().overlaps(being.getTalkingBounds())) {
       canTalk = true;
       talkAbleBeing = being;
       // Break out of the NPC loop
       break;
}

I'm not entirely sure, but you should still be able to iterate through all of the players? If not you may have to break out of both of the loops. Hopefully I helped.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.