Posts Tagged ‘snap’

Simple drag and drop with snap-to-tiles in XNA

Saturday, July 14th, 2012

If you need to create a tile-based editor, or for some other reason need to show selected tiles based on the mouseposition – here’s some code to help you do that Smile.

The most basic part of the code is figuring out what tile you are over by doing an integer division using the tile size. Let’s say your mouse is at (x=432,y=197) and each tile is 64x64 pixels. Which square is the mouse over?

well 432 / 64 = 6.75, but if this is done using two integers (int in C#), the decimal part is removed and we’re left with 6. The same with the y-part 197 / 64 = 3.078125 which is  3 without the decimal part.

Often however, you don’t want the map to start in the upper lefthand corner of the screen, so we need to subtract the position of the map from the coordinates.

This gives us something like this:


… where you subtract the top and left from the mouse’s coordinates before doing the integer division to find the square’s coordinates.

Here's the code above as a method which given the coordinates of the mouse, returns the row and column in the map:

//get the column/row on the board for a given coordinate
Vector2 GetSquareFromPosition(Vector2 position)
    //adjust for the boards offset (_boardPosition) and do an integerdivision
    return new Vector2(
    (int)(_mousePosition.X - _boardPosition.X) / _tileSize,
    (int)(_mousePosition.Y - _boardPosition.Y) / _tileSize);

Another noteworthy codesample

Making a “chessboard” out of the same Texture2D by alternating based on whether the column + row of a square is even or odd (by using the modulus “%” operator).

The modulus operator gives what is left after an integer division, so if you take an even number modulo 2 the remainder is zero, the remainder of an odd number modulo 2 is one.

float opacity = 1f;

//if we add the x and y value of the tile
//and it is even, we make it one third opaque
if ((x + y) % 2 == 0)
    opacity = .33f;
    //otherwise it is one tenth opaque
    opacity = .1f;

//draw the white square at the given position,
//offset by the x- and y-offset, in the opacity desired
spriteBatch.Draw(_whiteSquare, squareToDrawPosition, Color.White * opacity);

You can find the code here