0
\$\begingroup\$

I want to be able to click and hold on a certain point and mark it as startPosition. Then, while the mouse is held down and moved, mark that second position as endPosition.

When the mouse is finally released, I want to get all the positions between those two points.

Here is my code so far:

for (float x = startPosition.x; x <= endPosition.x; x++)
        {
            for (float y = startPosition.y; y <= endPosition.y; y++)
            {
                Vector3Int newPosition = Utilities.GridPosFromWorldPos(new Vector2(x, y));
                if (!selectedPositions.Contains(newPosition)) { selectedPositions.Add(newPosition); }
            }
        }

This works only when dragging up and/or to the right. As soon as I try to go to left or bottom, the endPosition coordinates become smaller than the startPosition coordinates, which breaks the for loop.

How can I solve this?

\$\endgroup\$
1
\$\begingroup\$

Solved like this:

        Vector3 lowerLeftTile = new Vector3(Mathf.Min(startPosition.x, endPosition.x), Mathf.Min(startPosition.y, endPosition.y));
        Vector3 upperRightTile = new Vector3(Mathf.Max(startPosition.x, endPosition.x), Mathf.Max(startPosition.y, endPosition.y));

        for (float x = lowerLeftTile.x; x <= upperRightTile.x; x++)
        {
            for (float y = lowerLeftTile.y; y <= upperRightTile.y; y++)
            {
                Vector3Int newPosition = Utilities.GridPosFromWorldPos(new Vector2(x, y));
                if (!selectedPositions.Contains(newPosition)) { selectedPositions.Add(newPosition); }
            }
        }
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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