void Robot::update(Ogre::Real dt) { switch(state) { case STAND: animationState->addTime(0.0001f*speed*dt); if (foundTarget()) setState(SEEK); else if (rand() % 400 == 1) setState(WANDER); break; case WANDER: { Ogre::Real dist = targetLocation.distance(this->getPosition()); if (dist < speed * dt) { setPosition(targetLocation); if (rand() % 5 != 1) setState(STAND); else setState(WANDER); } else { Ogre::Vector3 dir = (targetLocation - getPosition()).normalisedCopy(); this->translate(dir * speed * dt); animationState->addTime(0.0001f*dt); } if (foundTarget()) setState(SEEK); break; } case SEEK: { Ogre::Vector3 targetDiff = target->getPosition() - this->getPosition(); if (targetDiff.length() > 20) { setState(WANDER); } else if (targetDiff.length() > 5) { setVelocity(Ogre::Vector3::ZERO); } break; } } }
int search(struct position source, struct position target, int (*blocked)(struct position)) { struct position current; current = source; Dict d; d = DictCreate(); PQ* q; q = initQueue(); heapNode hn; hn.distFromSource = 0; hn.value = abs(current.x - target.x) + abs(current.y - target.y); hn.pos = current; enqueue(hn,q); DictInsert(d,current.x,current.y,hn.distFromSource); while(q->size) //stops when priority queue is empty { int i; hn = dequeue(q); current = hn.pos; if(foundTarget(current,target)) //hooray! target found!! { DictDestroy(d); destroyQueue(q); return hn.distFromSource; } for(i = 0; i < 4; i++) //for loop explores all the four neighbors defined as 0...3 { struct position neighbor = createNeighbor(current,i); int dictSearchDist = DictSearch(d,neighbor.x,neighbor.y); if(!blocked(neighbor) && dictSearchDist < 0) //add the neighbor to PQ { DictInsert(d,neighbor.x,neighbor.y,hn.distFromSource + 1); heapNode node; int distToTarget = abs(neighbor.x - target.x) + abs(neighbor.y - target.y); //manhattan distance node.value = (hn.distFromSource + 1) + distToTarget; node.pos = neighbor; node.distFromSource = hn.distFromSource + 1; enqueue(node,q); } else if(dictSearchDist >= 0) { if(dictSearchDist > hn.distFromSource + 1) { DictInsert(d,neighbor.x,neighbor.y,hn.distFromSource + 1); heapNode node; int distToTarget = abs(neighbor.x - target.x) + abs(neighbor.y - target.y); //manhattan distance node.value = (hn.distFromSource + 1) + distToTarget; node.pos = neighbor; node.distFromSource = hn.distFromSource + 1; enqueue(node,q); } } } } DictDestroy(d); destroyQueue(q); return NO_PATH; }