Sorry your browser is not supported!

You are using an outdated browser that does not support modern web technologies, in order to use this site please update to a new browser.

Browsers supported include Chrome, FireFox, Safari, Opera, Internet Explorer 10+ or Microsoft Edge.

Newcomers DBPro Corner / A forumula for finding the nearest "Character" to a "Monster" on a 2d grid

Author
Message
jasuk70
21
Years of Service
User Offline
Joined: 3rd Dec 2002
Location: Hemel Hempstead
Posted: 6th Aug 2004 01:26
If anyone is interested I've been working on a formula to find the nearest player to a monster on a square grid (Basically a 2d array). I though I'd share it. It's not exactly code so I thought I'd put it in the newcomers forum incase it helps anyone else.

Basically you get the difference between the monsters X coordinate and the characters X coordinate and call it xDiff, do the same with the y coordinates and call it yDiff, then work out the difference between xDiff and yDiff call that zDiff. Then add xDiff, yDiff and zDiff and that will give the character a score. If you do this to all the characters then the nearest one is the one with the lowest score.

so for example



The above grid shows the following:

x,y
5,4 - Monster
1,2 - Character 1
1,4 - Character 2
2,5 - Character 3
3,6 - Character 4

So using the above formula.

The Difference between Monster X and Character 1 X is 4 so xDiff=4
The Difference between Monster Y and Character 1 Y is 2 so yDiff=2
The Difference between xDiff and yDiff is 2 so zDiff=2
So the score for Character 1 is xDiff+yDiff+zDiff which =8

Using the same methods the others have been calculated below

Character 1 Score=(4+2+2)=8
Character 2 Score=(4+0+4)=8
Character 3 Score=(3+1+2)=6
Character 4 Score=(2+2+0)=4

This shows that Character 4 is the nearest character. If you then divide the score by 2 then that is the number of moves that monster will need to be on the same square as the character as long as diagonal moves are allowed.

Jas

----
"What is this talk of 'release'? Klingons do not'release' software. It escapes leaving a bloody trail of developers and quality assurance people in its wake!"
Phaelax
DBPro Master
21
Years of Service
User Offline
Joined: 16th Apr 2003
Location: Metropia
Posted: 6th Aug 2004 10:01 Edited at: 6th Aug 2004 10:01
You're making it way to complicated. Since you're only comparing distances, and you don't need the actual distance really, then that'll save you from using sqrt().

distance = (characterX - monsterX)^2 + (characterY - monsterY)^2

So lets assume that you've found all the distances of each character and put them in an array.

The closest character to the monster is "closest_character", and it's "sqrt(current_closest)" units away.

"eureka" - Archimedes

Login to post a reply

Server time is: 2024-11-27 04:57:23
Your offset time is: 2024-11-27 04:57:23