iphone app - maze solving
I'm working on an iPhone game with a bunch of mazes, and there's this villain who chases you within the maze.
I'm not using OpenGL ES nor tile map,so currently collision detection is performed by the xcode's CGRectsIntersectsRect function with each wall being an IB variable, kind of like this:
float hunterdiffx = abs(hunter.center.x - hunterDest.x);
float hunterdiffy = abs(hunter.center.y - hunterDest.y);
if((hunterdiffx!=0.0)&&(hunterdiffx>(1.0*diffy))&&(!hunterCollided)){
//NSLog(@"diffx >");
hunterVel.y = 0;
if(hunterDest.x>(hunter.center.x+3)){
//NSLog(@"x >");
hunterVel.x = 3;
}
else if(hunterDest.x<(hunter.center.x-3)){
//NSLog(@"x <");
hunterVel.x= -3;
}
//when rabbit reaches the destination
else if((hunter.center.x>(hunterDest.x-3)) && (hunter.center.x < (hunterDest.x+3))){
//NSLog(@"x =");
//NSLog(@"one side reach");
hunterVel.x = 0;
hunterVel.y = 0;
}
}
and
if(CGRectIntersectsRect(hunter.frame, border1.frame){
hunterCollided = TRUE;
if(hunterVel.x==0){
NSLog(@"vertical collision");
if(hunterVel.y>0){
hunter.center = CGPointMake(hunter.center.x, hunter.center.y -10);
}
if(hunterVel.y<0){
hunter.center = CGPointMake(hunter.center.x, hunter.center.y +10);
}
hunterVel.y=0;
if(hunterDest.x > hunter.center.x){
hunterVel.x=3;
}
开发者_Python百科 if(hunterDest.x < hunter.center.x){
hunterVel.x=-3;
}
}
// ...
}
This, as expected, leads to a very stupid behavior of the hunter, and now I'm wondering, since I'm not using tile map and cannot just use arrays to represent hunter's tries, could there be any algorithmic approach that lets the hunter find the right path within the maze?
I've struggled with a lot of math, and my brain is now malfunctioning. Please help me if you have any idea.
Collision detection using CGRectIntersectsRect is a really bad idea... because you'll have to keep track of every object around your moving sprite and check for rect intersection avery time...
you're probably doing this because you're already familiar with UIKit/CoreGraphics and dont want to take OpenGLES's steep learning curve....
but you can use out of the box collision detection (or physics in general) from third party libraries like Cocos2D.. it will take a little while to learn but will give you a robust solution....
thats just my opinion..
精彩评论