Making Decisions

Making decisions is an easy part, but as we've talked about, it's also easy to make creatures too smart. Obviously, you don't want to make a new decision every frame, so your code should provide limits so that decisions are made on a periodic basis—say, every second or so. You can make "dumb" creatures have a longer decision period. How often the bots make a decision is just one of those things you'll have to tweak until you get the right feel. Listing 13.8 has some sample code you'll use for decision making in the AIBot. Here, a special state called DECISION_READY is used to signify that a decision needs to be made. The bot makes decisions every few seconds (based on decisionTime) but makes decisions more often if it's idle. In this manner, it can quickly move to other states if it notices the player. Decisions are also made when you're done with the path you're traveling on (from the code in the PathBot class).

Listing 13.8 Decision Making in AIBot
// time (milliseconds) between making decisions long decisionTime;
...
public void update(GameObject player, long elapsedTime) {
 elapsedTimeSinceDecision+=elapsedTime;
 elapsedTimeInState+=elapsedTime;
 timeSincePlayerLastSeen+=elapsedTime;
 // if idle and player visible, make decision every 500 ms
 if ((aiState == NORMAL_STATE_IDLE ||
 aiState == NORMAL_STATE_PATROL) &&
 elapsedTimeInState >= 500)
 {
 aiState = DECESION_READY;
 }
 // if time's up, make decision
 else if (elapsedTimeSinceDecision >= decisionTime) {
 aiState = DECESION_READY;
 }
 // if done with current path, make decision
 else if (currentPath != null && !currentPath.hasNext() &&
 !getTransform().isMovingIgnoreY())
 {
 aiState = DECESION_READY;
 }
 // make a new decision
 if (aiState == DECESION_READY) {
 elapsedTimeSinceDecision = 0;
 if (canSee(player)) {
 setAiState(chooseBattleState(), player);
 }
 else if (timeSincePlayerLastSeen < 3000 ||
 canHear(player))
 {
 setAiState(NORMAL_STATE_CHASE, player);
 }
 else {
 setAiState(NORMAL_STATE_IDLE, player);
 }
 }
}


When making a decision, the bot chooses from a battle state, a chase state, or an idle state. If the player is visible, it picks a battle state. If the player was visible recently (in the last 3 seconds) or if the player is heard, the bot chooses the chase state. If none of those conditions are met, it chooses the idle state. But what happens when a bot chooses a state? You have to make the bot actually perform an action, with most of the actions being some sort of movement. This is where patterns come in.

Screenshot


   
Comments