Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm trying to place different objects in the game area like a grid, but I have some problem with my method that creates this objects and there positions. I'm trying to store each new positions in a List and then compare each new positions with the ones in the List before it's OK to use it as a new position in the grid of the game area. I only want to use each random position once. Help is preciated! Thanks!

Perhaps ther is a better way to do this?

    public void AddItemsToGameArea(ContentManager content)
    {
        foreach (string buildingPart in contentHouseOne)
        {
            Vector2 newPosition = NewRandomPosition;
            if (!checkPreviousPositions)
            {
                listHouseParts.Add(new HousePart(content, buildingPart, newPosition));
                listUsedPosition.Add(newPosition);
                checkPreviousPositions = true;
            }
            else
            {
                for (int i = 0; i < listUsedPosition.Count(); i++)
                {
                    // Check?? 
                }

            }
        }
    }

    public Vector2 NewRandomPosition
    {
        get
        {
            return new Vector2(gridPixels * Game1.random.Next(1, 8), gridPixels * Game1.random.Next(1, 8));
        }
    }
share|improve this question
    
When you say "Compare" what exactly is it you're trying to compare? –  Shaktal Jul 29 '12 at 13:36

2 Answers 2

From your code, it looks like one can create a conceptual grid, index it, and then convert a grid index to a vector position. If so, then your problem is to choose random unique grid indices from a given range of indices. In other words, you want to create a random permutation of the indices in this range.

Here is a code sample on stackoverflow for C#, but I have not checked the performance characteristics of shuffle.

share|improve this answer

From your code I can understand that you might be comparing the floats directly. Comparison will not directly as you think in case of floats.

Try checking for the difference and decide whether they are equal or not. Because floating point precision is a problem all the times.

Just go through these links which a programmer must know. http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

PS: As its tagged XNA, vector2 has floats as attributes. Please complete your question for clear details.

Hope this helps.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.