- Home /
Bounds of players on screen
Well hello there, I am trying to get the furthest left and furthest right player on the screen (this is a 2D platformer so math is simple) but I'm having an issue with my code. This is supposed to find the furthest indexed player to the right and the left on the screen and it works for the furthest RIGHT as far as I can tell but it doesn't always detect the LEFT most character, it seems to skip an index. I know theres a logical flaw here I'm just failing to find it at the moment.
if(posPrev == 0) posPrev = players[0].transform.position.x; for(int i = 0; i < numPlayers; i++) { posCur = players[i].transform.position.x;
if(posCur > posPrev)
largeIndex = i;
if(posCur <= posPrev)
smallIndex = i;
posPrev = posCur;
}
Answer by Owen-Reynolds · Mar 26, 2011 at 06:42 PM
posPrev is always the x-coord of the player just before you. The line if(posCur > posPrev) says you are the new winner if you beat the last guy, not the best so far. If you run it on enough inputs, you'll see it can be wrong on L or R (ex: 3,9,6,7) says 6 is left (less than 9) and 7 is right (more than 6.)
The standard "find best/worst array search" closest to what you have is this:
// Assume item 0 is the furthest left and right, for now:
float largeX = players[0].transform.position.x; // save index and pos of largest
int largeIndex = 0;
float smallX = players[0].transform.position.x; // same for smallest
int smallIndex = 0;
for(int i = 0; i < numPlayers; i++)
{
int posCur = players[i].transform.position.x;
if(posCur > largeX) {
largeIndex = i; largeX = posCur; // update index and pos of new largest
}
else if(posCur < smallX) {
smallIndex = i; smallX = posCur; // update index/pos of new smallest
}
}
Answer by Bampf · Mar 26, 2011 at 06:22 PM
Might be an initialization problem. You are initializing posPrev, but not largeIndex and smallIndex, so (depending on the rest of your code) it's possible that old values will leak through.
One way to do this would be to set largeIndex and smallIndex initialized to 0 when posCur is initialized to players[0].transform.position.x. (You could also start your loop at i = 1 in that case.)
I'm also confused by the first line, the IF condition. Why the test for posPrev == 0?
I had largeIndex and smallIndex initialized in Start() to 0, sorry I didn't post that.
$$anonymous$$y point was you need to reset them every time you run your loop, not just in Start(). The solution posted by Owen does exactly that (as well as the other fix.)
Your answer
Follow this Question
Related Questions
Make object transparent when between camera and player 11 Answers
Clarification with Texture2D.ReadPixels. 1 Answer
Camera watching inbetween the player and cursor 1 Answer
What is the typical setup for switching between third and first person, in terms of model culling? 0 Answers
Multiplayer| Attaching camera to player (if i am the owner 1 Answer