adityaravishankar / command-and-conquer

Command & Conquer in HTML5/Javascript
777 stars 170 forks source link

findRefineryInRange(hero) and findTiberiumInRange(hero) should use pathing instead of distance #42

Open jovoud opened 12 years ago

jovoud commented 12 years ago

[code] function findRefineryInRange(hero){ if(!hero){ hero = this; } var currentDistance; var currentRefinery; for (var i=0; i < game.buildings.length; i++) { var building = game.buildings[i]; if (building.name == 'refinery' && building.team == hero.team){ var distance = Math.pow(building.x-hero.x,2)+Math.pow(building.y-hero.y,2); if (!currentDistance || (currentDistance > distance)){ currentRefinery = building; currentDistance = distance; }
} }; return currentRefinery; }

[/code]

In the current first level this isn't really a problem, but when you play in big maps this can cause your harvester to go to the wrong refinery/tiberium. Why not use the A* pattern here and remember the path?

Let's say this map

00harvester0000000000tiberium10000000 0000000000000000000000000000000000 1111111111111111111111111111110000 000tiberium2000000000000000000000000

in this case the harvester will go to tiberium2 because the function says it's closer, but in fact there is a wall (represented by 1's here) here so the harvester will go all arround (using the A) the wall to tiberium2. Why not use the A to search for this as well and then remember the path somehow that it doesn't need to be calculated every gamecycli?

adityaravishankar commented 12 years ago

I thought I only did findTib /findRef if it wasn't already set. After that, it always goes to the stored tib/ref (I store from and to in the harvester)

jovoud commented 12 years ago

if you are going to use it in this form it should be: var distance = Math.pow(Math.pow(building.x-hero.x,2)+Math.pow(building.y-hero.y,2),0.5); You forgot the sqrt... at line 2673 you did use the sqrt ie.

But still when looking for new tiberium or a new refinery, it's best to use the A* algortihm that's implemented as well. Why make use of a simple sqrt(a²+b²) algorithm when you can use A* to find the best optimum? it doesn't really matter cpu times wise because there are tons of A* paths being calculated all the time.

adityaravishankar commented 12 years ago

well I figured if a <b then a^0.5 is less then b^0.5 .... No sense putting an unnecessary square root when comparing the squares is enough.....

As far as switching to pathfinding is concerned, it is something I will be doing in a future update... Along with not being able to find tiberium that is under fog....

For now, I am focusing on the more critical performance issues... :)

jovoud commented 12 years ago

Hehe it's all about the priorities :). In 2 weeks I've a lot of spare time, ill help you fix some of these bugs.