The post Shooting rays through tilemaps appeared first on GameDev<T>.

]]>For this **we need to know all the tiles the ray travels through**, and ideally in the order it travels through them, so that we can abort early in case of a collision.

This is exactly the algorithm we will implement here.

*Note that this algorithm is by no means original. For example James MCNeill posted about it back in 2007. I hope that my spin on it will still be useful to people.*

The idea behind the algorithm is easy: we start with the tile that the ray starts in. From there **we calculate the next horizontal and the next vertical intersection of the ray with the grid of the tilemap**.

Depending on which is closer we know what step to take: a vertical intersection means we take a horizontal step, and vice versa.

Let us start with pseudo code and get some boiler plate code out of the way before we look at the heart of the algorithm.

First we will convert the coordinates of the ray to the coordinates of the tilemap, and get the locations of the starting and ending tile.

```
start = positionToTileSpace(ray.Start)
end = positionToTileSpace(ray.Start + ray.Vector)
diff = end - start; // we will need this later
startTile = tileAt(start)
endTile = tileAt(end)
```

By taking the Manhattan distance between these two, we know how many tiles we will have to iterate.

```
tileDifference = endTile - StartTile
tileCount = abs(tileDifference.X) + abs(tileDifferenceY) + 1
```

**Knowing the total number of tiles, we can make an easy optimisation**: If the tile count is 1, we simply return the starting tile, because the ray does not leave it. If it is 2, we can return the starting and end tile, and are done for the same reason. In fact, we can return the first tile in any case, since we will have to return it first no matter what.

```
yield return startTile
if (tileCount <= 2)
if (tileCount == 2)
yield return endTile
yield break
```

*I use the C# yield return/yield break syntax to indicate enumerating elements and stopping enumeration respectively.*

We are almost ready to look at the actual algorithm. One more thing we need to prepare is the sign/direction of the horizontal and vertical steps. We can do this easily by taking the sign of the `tileDifference`

components we calculated above.

```
tileStepX = sign(tileDifference.X)
tileStepY = sign(tileDifference.Y)
```

Let us now jump around the code a bit. **Since we know the number of tiles we are going to enumerate already, we can iterate them in a simple for loop.** In fact, we iterate two less items in our loop, since we already returned the starting element and can return the end element in the end without having to calculate it.

```
// some more preparation here in a bit
for (i = 2 to count (exclusive))
step to next tile
yield return that tile
yield return end tile
// end of function
```

To be able to know which step to take with every iteration of our loop, we have to keep track of them. **Instead of doing any math with actually calculating the intersection points and comparing distances, we can make use of the following facts to simplify the algorithm**:

- consecutive intersections of the ray with grid lines of the same direction are all at the same distance to each other, and
- this is still true if we deal not with coordinates along the x and y axis, but
**instead work in a single dimensional space aligned to the ray**.

Given this, we can calculate the intersections along the actual ray, where we define the starting point as 0, and the end point as 1 on our imaginary axis.

What we now need is to calculate the the step size for both kinds of grid-line intersections along that axis, and since we allow the ray to start with an arbitrary position, we have to also calculate the first intersection.

Calculating the step size is easy, since **we merely have to transform each component of the difference vector to the new coordinate system**. Since in that system, the vector is of length 1, we perform this transformation by dividing 1 by the difference vector components.

To calculate the first intersection, we can determine the position of the starting point within the starting tile on a scale from 0 to 1, which in the tile coordinate system is equivalent to taking the modulus of the starting coordinates with 1.

Note that the exact calculation is slightly different depending on whether the difference vector component is positive or negative (i.e. if the ray is shooting left or right, up or down).

Otherwise the calculation is the same for both x and y, so we can abstract it into its own function.

To make clear what values represent x or y coordinates, here is that functions written for the x case.

```
getIntersectParameters(startX, diffX)
if (diffX == 0)
intersectXStep = float.NaN
nextIntersectX = float.PositiveInfinity
return (intersectXStep, nextIntersectX)
startXFraction = startX - floor(startX)
if (diffX > 0)
intersectXStep = 1 / diffX
nextIntersectX = (1 - startXFraction) * intersectXStep
else
intersectXStep = -1 / diffX
nextIntersectX = startXFraction * intersectXStep
return (intersectXStep, nextIntersectX)
```

Note how I handle the case where the difference along this component is 0. While possibly rare, we have to make sure that we do not end up in some sort of infinite loop. By setting the next step intersection to infinity, the other step component will always have a smaller step, so that the loop always steps into the correct direction.

With the method above in place, we can fully implemented the algorithm we indicated above.

```
tileX = startTile.X
tileY = startTile.Y
intersectXStep, nextIntersectX = getIntersectParameters(start.X, diff.X)
intersectYStep, nextIntersectY = getIntersectParameters(start.Y, diff.Y)
for (i = 2 to count (exclusive))
if (nextIntersectX < nextIntersectY)
tileX += tileStepX
nextIntersectX += intersectXStep
else
tileY += tileStepY
nextIntersectY += intersectYStep
yield return (tileX, tileY)
yield return end tile
// end of function
```

And that is all!

If you are interested, feel free to take a look at my full implementation of this algorithm as part of my game Centipede, which is entirely open source on GitHub

In this post we developed an algorithm to efficiently determine all tiles intersecting a ray, iterating them in the correct order, and one at a time, which allows for early determination, if for example a collision is detected.

*If this has been interesting or useful for you, make sure to share the post on your favourite social media.*

And of course feel free to ask any questions or give any feedback in the comments below.

Enjoy the pixels!

The post Shooting rays through tilemaps appeared first on GameDev<T>.

]]>The post Tilemaps: circular range queries appeared first on GameDev<T>.

]]>To make the best use of tilemaps, **we need query algorithms that allow us to return tiles in a given area of the tilemap**, so we can deal with those tiles specifically, without having to look at other tiles.

**These algorithms have to be efficient and correct**, meaning that they should consider as few tiles as possible, and return exactly those we are interested in, all with the minimum amount of work.

If we store game objects in the tiles they are in, **this will allow us to quickly access all objects in a certain area** – and do so much more efficiently than having to loop over all game objects and check each.

Recently, I wrote on how we can efficiently return all tiles intersecting an axis aligned rectangle.

The idea behind that algorithm was as follows:

- Take opposite corners of the rectangle, and find the tiles they are in
- Consider the rectangle of tiles, spanned by these two
- Enumerate all those tiles in a simple nested for-loop

Baring some special cases and considerations, it was as simple as that.

We will take this as a starting point for our implementation today.

Given our circle that we want to intersect with our tilemap, **we can trivially find the smallest axis aligned rectangle – and thus square – containing the circle**.

We can use the algorithm from the other post to enumerate all tiles in that square.

The only thing left to do is check if each tile intersects with our circle, and if so, return it.

To check if a tile intersects our circle, we will check for intersection between the circle and the rectangle encompassing the tile.

I did some research and **there are multiple approaches with different advantages and disadvantages for this check**. The one I will explain here is the most efficient, but also the one giving us the least information. It will merely return whether the circle and rectangle intersect or not. Luckily that is all we care about here.

**The idea behind this algorithm is to use the symmetry of the axis aligned rectangle**. If we consider the center of the rectangle to be the center of the coordinate system, it is symmetrical along both axis.

That means that **we can fold along both axis to map all quadrants onto a single one**. If we also fold the circle into the same quadrant, we simplify the problem by only having to check for intersection in that single quadrant.

We can do this folding simply by taking the absolute value of our coordinates (after shifting our coordinate system to the center of the square).

Naturally, the coordinates of the center of the square will be (0, 0) after that shift, so we really only have to consider the vector between the centers of the two objects.

Another important fact is that **the circle will intersect the rectangle if and only if the distance between the center of the circle and the closest point in the rectangle to it is smaller than the radius of the circle**.

Due to taking the absolute value of that vector, we now only have to deal with a single quadrants, which allows us to determine this closest point in a relatively easy way.

We subtract the half-size of the rectangle (half its width and height) from the already positive absolute difference vector we determined earlier.

This is equivalent to another coordinate system shift, where we now align the origin with the closest of the rectangles corners to the circle.

If either of the coordinates of the circle’s center is now negative, that means that the circle’s center is on one of the four sides of the rectangle.

For example, if the circle’s center now has a negative x-coordinate, it’s x coordinate is between the left and right values of the rectangle. In that case, we only have to check the straight distance between the center and the top side of our rectangle. If that is less than the circle’s radius, they intersect. And the same check works of course for the y axis.

If the circle’s center coordinates are positive, the circle lies outside these areas where we can perform the simple distance check. However, this means that the closest point to the circle’s center on the rectangle is the rectangle’s corner, and testing those two for their distance can easily be done with Pythagoras’ theorem.

In fact, as it happens, **we can combine both these checks into one by clipping the vector we just calculated to the positive range**, and then calculating the length of that vector and comparing it against the radius of the circle.

This clearly works in the case where the vector was already positive, but it also works in the negative case, since we essentially throw out the affected coordinate by setting it to 0. The resulting check will simply check the remaining coordinate against the radius, which is exactly what we needed.

Throwing this all together, here is this method fully implemented:

```
private static bool rectIntersectsCircle(
Vector2 rectCenter, Vector2 rectHalfSize,
Vector2 circleCenter, float circleRadiusSquared)
{
// shift coordinate system to rectangle center
var diff = rectCenter - circleCenter;
// fold circle into positive quadrant
var diffPositive = new Vector2(
Math.Abs(diff.X),
Math.Abs(diff.Y)
);
// shift coordinate system to rectangle corner
var closest = diffPositive - rectHalfSize;
// set negative coordinates to 0
// so they do not affect the check below
var closestPositive = new Vector2(
Math.Max(closest.X, 0),
Math.Max(closest.Y, 0)
);
// perform distance check
return closestPositive.LengthSquared <= circleRadiusSquared;
}
```

Note that for simplicity – and efficiency – I already supply the parameters to their method in a preprocessed form. This allows us to re-use the squared radius, and half rectangle size when checking for intersections with multiple rectangles – or tiles in out case.

**With this method, we can now check all our enumerated tiles, and return only those that actually intersect the circle.**

Note however, that this is somewhat inefficient, since we will check a large number of tiles that are clearly inside the circle. We can do better.

**Instead of checking all tiles, we can consider each row of the rectangle**, and find the first and last tile that intersect the circle in each row. Once we know those, the tiles in between necessarily intersect the circle as well. *This has to do with the convex nature of a circle. The proof is left to the reader.*

Finding the first and last tile intersecting the circle is very easy as the following pseudo code shows.

```
foreach (row in tile rectangle)
{
xStart = row.firstIndex
xEnd = row.lastIndex
while(tile at (xStart, row.y) does not intersects circle)
xStart++;
while(tile at (xEnd, row.y) does not intersect circle)
xEnd--;
enumerate tiles from xStart to xEnd (including)
}
```

An actual implementation is slightly more complicated, at least if it tries to be efficient and not constantly recalculate tile coordinates. You can see my final implementation on GitHub.

The algorithm above is fairly efficient and checks only a few too many tiles for circles in the size ranges I am interested in (around 10-15 tiles across at most).

However, **if we are dealing with much larger circles, or much smaller tiles, it may be a good idea to further optimise**.

Note how the two loops finding the starting and ending tile of each row are linear search algorithms. As such, we can optimise them by using a more efficient one, like a binary search.

Additionally, we could start the search with a better estimate than the outside of the rectangle. For example the diagonal from the top most to the left most point of the circle would provide a much better approximation of the circle itself.

Or, we could even go as far and use trigonometric functions to calculate the actual intersection of the tilemap’s grid lines and the circle, and use these either as a starting point, or if we are careful as a complete solution.

These are all ideas for future posts however.

In this post we saw how we can test circles and rectangles for intersection with each other, and used this to enumerate all tiles in a tilemap that intersect a given arbitrary circle.

*If this has been interesting or useful to you, please share this post on your favourite social media.*

Next time we will take a look at another kind of tilemap range query: finding all tiles intersecting an arbitrary ray.

Enjoy the pixels!

The post Tilemaps: circular range queries appeared first on GameDev<T>.

]]>The post Tilemap – tiles intersecting rectangle appeared first on GameDev<T>.

]]>This is exactly what we will write code for here.

The requirements for our code are rather simple and straight forward.

**Given a regular, rectangular grid or tilemap, and an arbitrary rectangle, both aligned to the same axes, we would like to enumerate all tiles that are intersected by that rectangle.**

For now we do not care about the order of the tiles, but we do care that there are no false positives or false negatives.

The simplest approach would be to enumerate all tiles in our tilemap, and then only pass on those that intersect the rectangle.

In pseudo code this would look something like this:

```
getAllTilesInRectangle(tilemap, rectangle)
{
foreach(tile in tilemap)
if (tile intersects rectangle)
yield tile
}
```

Clearly, **this algorithm is very inefficient**. If our rectangle is small compared to the tilemap, we might enumerate a huge number of unnecessary tiles.

**Ideally, we want to only enumerate exactly those tiles we are interested in.**

In the case of intersection with an axis aligned rectangle, this is very easy to do.

All we need to do is **find the tiles containing the top-left and the bottom-right corners of the rectangle** (or top-right, bottom-left, as long as they are opposite).

The rectangle of tiles spanned by these two tiles necessarily encompasses the entire rectangle, since it is aligned to the axis. It cannot *break out* of that rectangle with any diagonal or curved sides.

This means that **we only have to enumerate the tiles inside that rectangle of tiles** to get exactly the tiles we are interested in.

We can do this easily by accessing the tilemap using x and y coordinates, and enumerating over these in a nested for-loop.

```
getAllTilesInRectangle(tilemap, rectangle)
{
tileTL = tile containing rectangle.TopLeft
tileBR = tile containing rectangle.BottomRight
for(y = tileTL.y to tileBR.y)
for(x = tileTL.x to tileBR.x)
yield tile at (x, y)
}
```

Note that it is important that we include the x and y values of the bottom-right tile in our loop.

Otherwise we will miss one row and one column.

When implementing this in real code it is also important to make sure that the first corner tile has lower coordinates than the second one, otherwise the for-loop with simply exit.

If this is the case, we can simply take different opposite corners of the rectangle. If the orientation of our rectangle is not known, we can always use `min`

and `max`

functions to select the smallest and the largest corner easily enough.

Lastly, since we are blindly calculating tilemap coordinates here, we may end up with tiles that are actually outside the tilemap, if it is possible for our rectangles to extend past the tilemap.

In most cases we probably want to not return such tiles, since it is bound to cause problems, when trying to access none existing tiles.

Below is an example implementation that takes all the mentioned subtleties into account. If this extra work is needed will largely depend on your used rectangle type, and whether you expose this method enough to be worried about someone running into the possibly edge cases.

```
IEnumerable<Tile> GetAllTilesInRectangle(
Tilemap tilemap, Rectangle rectangle)
{
var topLeft = tilemap.GetTileAt(rectangle.TopLeft);
var bottomRight = tilemap.GetTileAt(rectangle.BottomRight);
var xStart = topLeft.X;
var xEnd = bottomRight.X;
var yStart = topLeft.Y;
var yEnd = bottomRigt.Y;
if(xStart > xEnd)
Swap(ref xStart, ref xEnd);
if(yStart > yEnd)
Swap(ref yStart, ref yEnd);
for (int y = yStart; y <= yEnd; y++)
for (int x = xStart; x <= xEnd; x++)
{
if(tilemap.IsValidTile(x, y))
yield return tilemap[x, y];
}
}
static void Swap<T>(ref T one, ref T, other)
{
var temp = one;
one = other;
other = temp;
}
```

*Note that the use of a Swap helper method is of course not necessary, but I think it makes the code more readable, and it is a great method to keep in a static helper class to reuse in many other places of a bigger project.*

If we are discarding invalid tiles, **we may want to consider clamping our tile rectangle to only contain valid tiles in the first place**. That could be done by adding a call to the following method before the loop above.

```
void clipRectangleToTilemap(Tilemap tilemap,
ref xStart, ref xEnd, ref yStart, ref yEnd)
{
xStart = Math.Max(xStart, 0);
yStart = Math.Max(yStart, 0);
xEnd = Math.Min(xEnd, tilemap.Width);
yEnd = Math.Min(yEnd, tilemap.Width);
}
```

This method assumes that the valid coordinates of the tilemap range from 0 to width/height, but it can of course be changed to other ranges easily.

If we add a call to this method, we are guaranteed to only loop over valid tiles, which means that we can take out the condition checking every single tile in the loop, and simply return them all.

In this post we discussed how to iterate all tiles in a tilemap intersecting an arbitrary axis aligned rectangle.

*If you find the post useful, make sure to share it on your favourite social media.*

Next time we will expand on the above and look at how to efficiently return tiles intersecting an arbitrary circle instead.

Enjoy the pixels!

The post Tilemap – tiles intersecting rectangle appeared first on GameDev<T>.

]]>The post Keeping track of objects in a tilemap appeared first on GameDev<T>.

]]>

**Tilemaps are one of the must useful spacial acceleration data structures** in game development to the point where many classic and modern games rely partly or entirely on tilemaps for their game logic.

In some games, objects are always contained in exactly one tile. However, what if our objects can move freely and we simply use the tilemap as a quick-access structure?

Free moving objects that are not of zero width and height are always able to intersect multiple tiles, and will do so frequently while moving. If an object is in fact so large that it does not fit into a single tile, it will always intersect multiple.

**To accelerate finding objects in a certain area, each tile intersecting the object needs to have a reference to it.**

Let us develop an efficient algorithm for doing just that.

Our first implementation is relatively easy:

Every time our object moves, we can remove it from all tiles that it was contained in, and then add it to all tiles it intersects after the movement.

For example, using pseudo code:

```
field position
updatePosition(newPosition)
{
foreach(tile in this.intersectingTiles())
tile.Remove(this)
this.position = newPosition
foreach(tile in this.intersectingTiles())
tile.Add(this)
}
```

Simple enough.

But how do we determine the intersecting tiles? This is not very difficult either. We can simply determine the tiles that contain the top-left and bottom-right corners of our objects.

The rectangle of tiles spanned by those two points contains all the tiles our object intersects with (we are assuming our objects to be axis aligned rectangles here).

```
field position
field width
field height
intersectingTiles()
{
topLeft = position - (width, height) / 2
bottomRight = position + (width, height) / 2
tileTL = coordinates of tile at topLeft
tileBR = coordinates of tile at bottomRight
for(y = tileTL.y to tileBR.y (inclusive))
for(x = tileTL.x to tileBR.x (inclusive))
yield tile at x, y
}
```

The above algorithm works well. However, it does a lot of unnecessary work. Note how we have to find the list of intersecting tiles twice every time we run the algorithm, even though we could store the list of tiles – or to save space the rectangle of tiles after the movement for the next frame.

Once we keep track of that already, we can optimise further and only run the entire algorithm if the tile rectangle actually changed. For slow moving objects this will not be the case very often. They might only change their tile-intersection every few dozen frames. **Skipping all the list manipulation for the majority of frames will give us significant performance improvements.**

```
field position
field width
field height
field currentTileRectangle
updatePosition(newPosition)
{
this.position = newPosition
newRectangle = calculateCurrentTileRectangle()
if(newRectangle == currentTileRectangle)
return // nothing changed. done here.
foreach(tile in this.intersectingTiles(this.currentTileRectangle))
tile.Remove(this)
foreach(tile in this.intersectingTiles(newRectangle))
tile.Add(this)
this.currentTileRectangle = newRectangle
}
calculateCurrentTileRectangle()
{
topLeft = position - (width, height) / 2
bottomRight = position + (width, height) / 2
tileTL = coordinates of tile at topLeft
tileBR = coordinates of tile at bottomRight
return (tileTL, tileBR)
}
intersectingTiles(rectangle)
{
(tileTL, tilleBR) = rectangle
for(y = tileTL.y to tileBR.y (inclusive))
for(x = tileTL.x to tileBR.x (inclusive))
yield tile at x, y
}
```

Our code has gotten significantly longer with these improvements, however if we are dealing with many objects, the performance impact will justify this many-fold.

**When implementing the above algorithm, it is not unlikely that we may use linked lists to store the objects.** If we keep track of the list nodes the object is using, it will allow us add and remove the object from tile-lists in constant time.

Further, it also allows us to make another optimisation: Since we are now keeping track of the linked list nodes, we no longer have to enumerate the old rectangle of intersecting tiles. Our nodes will know the list they belong to, so that we can simply remove the nodes from all their lists in a tight loop.

Since we are trying to be efficient, **let us also reuse the linked-list nodes to not create unnecessary garbage collection pressure**. As an object enters a tile from intersecting multiple, this may cause some of the nodes to remain unused, and in the opposite case we will have to ensure that we have enough nodes for all the intersecting tiles.

Those checks can be added easily however.

```
field position
field width
field height
field currentTileRectangle
field linkedListNodes
updatePosition(newPosition)
{
this.position = newPosition
newRectangle = calculateCurrentTileRectangle()
if(newRectangle == currentTileRectangle)
return // nothing changed. done here.
this.currentTileRectangle = newRectangle
removeFromAllTiles()
ensureNodeCount(newRectangle.TileCount)
addToAllTiles()
}
removeFromAllTiles()
{
foreach(node in this.linkedListNodes)
node.List.Remove(node)
}
addToAllTiles()
{
i = 0;
foreach(tile in this.currentTileRectangle)
tile.Add(this.linkedListNodes[i])
i++
}
```

There is one last optimisation that I can think off, however I am not convinced it is really worth it, since it is both difficult to implement, and uses more complicated logic that may offset other performance gains.

The idea here is to compare the old and new tile rectangles not only for equality, but for their overlap as well. All tiles that are contained in both the rectangles are tiles that the object was and will remain intersecting.

That means that we would not have to remove and re-add the object to that tile.

In principle this might speed up the algorithm significantly, especially for large objects that are contained in many tiles.

And while the pseudo code for this algorithm is relatively easy, the enumeration of all tiles contained in one, but not the other rectangle will be a mess of special cases that I am not willing to tackle here today.

I hope this has been an interesting overview of how to keep track of large objects in a tilemap.

*If you think this post is useful, please share it on your favourite social media.*

Next week we will flip things around and instead of putting objects into tilemaps, we will discuss how to efficiently retrieve those objects again.

Enjoy the pixels!

The post Keeping track of objects in a tilemap appeared first on GameDev<T>.

]]>The post Using tilemaps as accelerating data structure appeared first on GameDev<T>.

]]>**We can use tilemaps as an accelerating data structure for many other systems like physics and AI**, by keeping track of what objects are contained within each tile of the tilemap.

Today, we will look into the different options for doing just that.

When developing a game or simulation **many different algorithms require access to lists of objects** to interact with. Often, objects only want to interact with a small subset of objects, based on some sort of criteria.

**Accelerating data structures allow us to get easier access to these sub-sets**, without having to iterate all existing objects and filter them by our given criteria.

In many cases, especially for the simulation of physics, the filtering criterion is based on proximity: We are interested in all objects close to a certain point, since these are the only objects that have a chance of interacting with our primary object through collisions for example.

*Note that everything below applies to non-physics algorithms as well. We will use physics merely as a convenient example that requires us to retrieve all objects within a certain area.*

**To make large scale physics simulations possible, a spacial acceleration data structure is critical**. Without it, we have to test each physical object against each other one which results in

However, if we are using an accelerating data structure, we can reduce that runtime to *O(n * k * r)* where *k* is the number of objects that our data structure returns (i.e. the objects close by) and *r* is the time it takes to retrieve each single of the *k* potential objects.

So, for example, in the case of our simple list of all objects, *k = n* since we have to enumerate all objects, and *r = 1* since each enumeration step is constant work. So, as expected the formula returns *O(n * n * 1) = O(n ^{2})*.

Of course **there are a number of different data structures we could use to accelerate our retrieval algorithm**. Each of these tends to come with different trade-offs in terms of memory usage, lookup time (*r*) and possible accuracy (bounds on *k*).

For example, a common data structure is the quad-tree, or oct-tree in three dimensions. Quad-trees split a large starting square into four smaller squares, and then recurse, splitting each square into smaller ones, until each square only contains a small number of objects. Oct-trees are similar, but split larger cubes into eight smaller ones.

Since each consecutive square is only half the size of the previous one, they decrease in size exponentially, and the lookup time *r* tends to be logarithmic in n: *r = O(log n)*.

There are also other structures based on trees, like the popular KD-tree, that behave similarly.

A great advantage of **trees like this is that they take relatively little memory, scale well even for large numbers of objects, and provide very accurate results for queries**. In terms of our runtime formula above, they are very good at keeping *k* as low as possible with the minor trade-off of a slightly higher *r*.

Overall, such trees will result in a runtime of *O(n * k * log n)* as per our formula above.

There is one problem with relatively complex data structures like trees however that we have not yet discussed: In a game environment we have to not only be able to access our subsets of objects quickly, but we also have to keep our accelerating data structures up to date to make this possible in the first place.

**Many of our relevant objects may be moving around the game world**, potentially at high speeds, so that **we have to make sure our data structure is accurate every single frame**.

While updating especially predictable data structures like quad-trees is not overly complex, each position update may result in up to *O(log n)* work – the amount of work it needs to remove and insert an object. That means that we we need to do an additional *O(n * log n)* work each frame. While this will not affect our overall runtime, it may still be significant when we are dealing with thousands of objects that we want to simulate in real time.

This is what brings us to tilemaps. Their common implementation as a two dimensional array means that they are a direct access table. In other words, **we can access any tile in constant time**.

Thus, if we store the list of all contained objects for each tile, this means that in our runtime formula, *r = 1*, since both the initial access of the tile, as well as each enumeration step takes constant time.

This seems like a clear advantage over trees as accelerating data structures.

However, **the great disadvantage of direct access tables are collisions** – unlike trees they can not adapt to many objects being very close to each other.

If we get a very tight grouping of objects, a tilemap will be forced to store these in just a few tiles, each of which will contain a possibly long list of objects. Trees on the other hand would simply split a few more times to make sure their leaf nodes only contain a few or a even a single element.

In terms of runtime this means that *k* will be larger when dealing with tilemaps.

However, **in most games, objects will only be grouped together to a limited extend**. By choosing a good size for the tilemap, we can put a very tight limit on *k* in most cases.

Further, updating the tilemap when an object moves can be done in constant time, as we will see below.

After this discussion of the advantages and disadvantages of different data structures, how do we actually keep track of what objects are in what tile?

Turns out we can go with a fairly straight forward approach: We simple keep a list inside each tile, and **every time an object moves to a different tile, we remove it from one list and add it to the other**.

Here is some pseudo code:

```
class Tile
{
List Objects;
}
class Object
{
Tile currentTile;
OnUpdatePosition()
{
Tile newTile = Level.GetTileAt(this.position);
if (newTile != this.currentTile)
{
this.currentTile.Objects.Remove(this);
newTile.Objects.Add(this);
this.cirrentTile = newTile;
}
}
}
```

The `GetTileAt()`

call which returns the tile containing a specific point is a very simple method which only has to transform our world coordinates into tile coordinates and return the appropriate tile – logic like this should come with any tilemap implementation or can easily be implemented on top of it.

They key points we have to look at closer are the calls to `Remove()`

and `Add()`

. If we indeed keep a C#-List, backed by an array, inside each tile, then the removing call has to both look for our object inside that list, and then move all objects after it by one to fill the gap inside the list.

That means that moving from one tile to another is not constant time, but actually linear in the number of objects in the tile that we left.

However, there is a solution: Instead, we can use a linked list and keep around the node used to keep our object in the list. If we have both the list and the node, removing it comes down to updating a few references, which is constant time.

*Note: While the theoretical runtime of using a linked list is better than that of an array backed one, in practice and with small numbers of objects, it might actually be significantly more efficient to use an array backed list. Enumerating linked lists can be significantly slower, and might easily overpower what we gain by not having to search through compress our lists on removal.*

In both cases **iteration will be linear in the number of objects in the list**, which is as good as it gets, resulting in our overall query runtime of *O(n * k * r) = O(n * k * 1) = O(n * k)* which is as good as we could hope for. This will result in great performance as long as we are able to limit our *k* by choosing an appropriate tilemap size.

Unfortunately, there are some caveats with the proposed solution. So far we have not actually looked at how to return objects inside a given range or area.

Further, all our objects currently can only be inside a single tile which is rather limiting and unrealistic when it comes to actual physical objects that take up space and could easily be intersecting multiple tiles.

These are important concerns which I will make sure to address in future posts.

*If you have found this interesting and would like to see the follow up posts expanding on how to use tilemaps as accelerating data structure, make sure to share this post on your favourite social media.*

Enjoy the pixels!

The post Using tilemaps as accelerating data structure appeared first on GameDev<T>.

]]>The post Mapping game coordinates to a tilemap appeared first on GameDev<T>.

]]>

We will start with the generic implementation of a tilemap from a recent post. Next to a basic `Tilemap<T>`

class we also created a `Tile<T>`

type which represents a reference to a specific tile in a tilemap.

We will use that type, as well as plain coordinates to interact with the class we will create.

The purpose of this class is to make it as easy as possible for us to work with our tilemap. We would like to get the tile for any game world coordinates, as well as get the position of any tile, and possibly more.

The basic implementation of our class will be relatively simple. It needs to know our tilemap, and we have tell it about the scale and offset to use for coordinate conversions.

The scale represents the size of each individual tile in game-world coordinates, and the offset determines where the tilemap is located with respect to the world’s origin.

In many games an offset of (0, 0) may be fine, but **it sometimes makes things easier to think of the game world centered around the origin**, extending equally in all directions. In that case we want to make sure the tilemap is centered around the origin as well.

Let us call the class `TilemapSpacialWrapper<T>`

where `T`

is the type of tile.

The class’ constructor could look something like this:

```
class TilemapSpacialWrapper<T>
{
private readonly Tilemap<T> tilemap;
private readonly Vector2 offset;
private readonly float tileSize;
private readonly float tileSizeInv;
private readonly float tileSizeHalf;
public TilemapSpacialWrapper(Tilemap<T> tilemap, Vector2 offset, float tileSize)
{
this.tilemap = tilemap;
this.offset = offset;
this.tileSize = tileSize;
this.tileSizeInv = 1f / tileSize;
this.tileSizeHalf = tileSize / 2f;
}
}
```

I am already pre-calculating the half and the inverse tile size here, since we will need them later, and pre-computing them will speed up our eventual coordinate conversions.

We could easily add further constructors that could do some of the work for us. For example, we might prefer specifying the size of the level as well as the size of the tiles, and have the level class create the tilemap for us.

Let us assume we mean also center the world and tilemap around the origin, in which case the constructor might look as follows.

```
public TilemapSpacialWrapper(float worldWidth, float worldHeight, float tileSize)
{
var tilesX = (int)Math.Ceil(worldWidth / tileSize);
var tilesY = (int)Math.Ceil(worldHeight / tileSize);
this.tilemap = new Tilemap<T>(tilesX, tilesY);
this.offset = new Vector2(tilesX, tilesY) * (-tileSize / 2);
this.tileSize = tileSize;
this.tileSizeInv = 1f / tileSize;
this.tileSizeHalf = tileSize / 2f;
}
```

With this data in place, we can now write methods to convert between the coordinate systems.

Here are some ideas for functionality I would like to expose:

- get the tile at a point in the world
- get the center position of a tile
- get the top left position of a tile

We can implement the first using indexers, and the other two using methods as follows.

```
public Tile<T> this[Vector2 point]
{
get { /* return tile at point */ }
}
public Vector2 GetTileCenter(Tile<T> tile)
{
/* get the center position of the tile */
}
public Vector2 GetTileTopLeft(Tile<T> tile)
{
/* get top left position of the tile */
}
```

To be able to implement these, we need to be able to convert between the two coordinate systems. Since we are dealing with two axis aligned euclidean spaces, we can use a very simple scaling for this.

```
private void tileSpaceToPosition(float tx, float ty, out float x, out float y)
{
x = tx * this.tileSize + this.offset.X;
y = ty * this.tileSize + this.offset.Y;
}
private void positionToTileSpace(float x, float y, out float tx, out float ty)
{
tx = (x - this.offset.X) * this.tileSizeInv;
ty = (y - this.offset.Y) * this.tileSizeInv;
}
```

Using these two methods, we can create one more useful helper function that will call `positionToTileSpace`

and convert the returned coordinates into proper tilemap coordinates (i.e. cast floating points coordinates to integers).

```
private void positionToTile(float x, float y, out int tx, out int ty)
{
this.tileSpaceToPosition(x, y, out x, out y)
tx = (int)x;
ty = (int)y;
}
```

With these helpers in place, we can implement our indexer and two methods from above.

```
public Tile<T> this[Vector2 point]
{
get
{
int x, y;
this.positionToTile(point.X, point.Y, out x, out y);
return new Tile<T>(this.tilemap, x, y);
}
}
public Vector2 GetTileCenter(Tile<T> tile)
{
return this.GetTileTopLeft(tile)
+ new Vector2(this.tileSizeHalf, this.tileSizeHalf);
}
public Vector2 GetTileTopLeft(Tile<T> tile)
{
float x, y;
tileSpaceToPosition(tile.X, tile.Y, out x, out y);
return new Vector2(x, y);
}
```

These are the basic but essential operations this wrapper class helps us perform.

Today we have looked at how to convert between single direct coordinates and tile coordinates when working with a tilemap.

We can expand the implemented class further to include not only single-tile queries, but range queries that return all tiles in a certain area, like a rectangle, or circle, or all tiles intersecting a ray.

But those are topics for future posts.

Enjoy the pixels!

The post Mapping game coordinates to a tilemap appeared first on GameDev<T>.

]]>The post Taking steps and other useful tilemap helpers appeared first on GameDev<T>.

]]>

The generic tilemap class we implemented last week came with the following small helper struct which represents a reference to a particular tile in a tilemap.

```
struct Tile<T>
{
private readonly Tilemap<T> tilemap;
public int X { get; }
public int Y { get; }
public Tile(Tilemap<T> tilemap, int x, int y) : this()
{
this.tilemap = tilemap;
this.X = x;
this.Y = y;
}
public T Value
{
get { return this.tilemap[this.X, this.Y]; }
}
}
```

Given such a type, I think **it would be great to be able to retrieve all tiles next to it**. We can of course do this easily, by constructing further instances of the reference struct with offset coordinates.

We could for example add the following property.

```
public IEnumerable<Tile<T>> Neighbours
{
get
{
yield return new Tile<T>(this.tilemap, this.x + 1, this.y);
yield return new Tile<T>(this.tilemap, this.x + 1, this.y + 1);
yield return new Tile<T>(this.tilemap, this.x, this.y + 1);
yield return new Tile<T>(this.tilemap, this.x - 1, this.y + 1);
/* etc. */
}
}
```

This works, but it feels somewhat hard-coded, and not very flexible.

**Something else that we may want to get from a tile is just a specific neighbour**, say the one to its right. Writing a method for this is difficult, since we have no good way of representing ‘one tile to the left’. Instead we could write properties for all the eight directions, but that again results in a lot of inflexible code.

Instead, let us represent the concept of ‘direction’ in the tilemap using a enumerator.

```
enum Direction : byte
{
Unknown = 0,
Right = 1,
UpRight = 2,
Up = 3,
UpLeft = 4,
Left = 5,
DownLeft = 6,
Down = 7,
DownRight = 8,
}
```

Given this, we can write a method with the signature `Tile<T> Tile<T>.Neighbour(Direction direction)`

which is much better.

Before we can implement that method however, we need a way to translate directions to actual x,y offsets in the tilemap.

Let us write another small helper type for this.

```
struct Step
{
public readonly sbyte X;
public readonly sbyte Y;
public Step(sbyte x, sbyte y)
{
this.X = x;
this.Y = y;
}
}
```

*I do not often expose the fields of structs directly, but in this case it really does not matter much.*

With this type, I would ideally like to write a method on `Direction`

to convert a given direction to a `Step`

value. ** enums do not allow for methods however, but we can use an extension method instead**.

```
static class Extensions
{
internal static readonly Step[] DirectionDeltas =
{
new Step(0, 0),
new Step(1, 0),
new Step(1, 1),
new Step(0, 1),
new Step(-1, 1),
new Step(-1, 0),
new Step(-1, -1),
new Step(0, -1),
new Step(1, -1),
};
public static Step Step(this Direction direction)
{
return DirectionDeltas[(int)direction];
}
}
```

Note that instead of using a number of `if else`

clauses, I instead use an array as a direct access table. We could also use a `switch`

statement which may be compiled even more efficiently.

**Using a direct access table like this is possible in the first place because we made sure to assign the values of Direction consecutive indices**.

With this in place, we can now write the following method in `Tile<T>`

.

```
public Tile<T> Neighbour(Direction direction)
{
return this.neighbour(direction.Step());
}
private Tile<T> neighbour(Step step)
{
return new Tile<T>(this.tilemap, this.X + step.X, this.Y + step.Y);
}
```

Whether or not to expose the functionality of `Step`

publicly is up to you. I consider it an implementation detail and hide it in our library.

With these helper types in place, we can now simplify our original property, enumerating all neighbours of a tile.

```
public IEnumerable<Tile<T>> Neighbours
{
get
{
for (int i = 1; i < 9; i++)
{
yield return this.Neighbour(Extensions.DirectionDeltas[i]);
}
}
}
```

Note how we skip the first element (index 0) of the array. That element corresponds to `Direction.Unknown`

and has a step of 0,0 which would simply return the same tile.

Another improvement we can make is adding another property that checks if the neighbours we are returning are actually valid tiles. That will prevent us from accidentally accessing tiles outside the tilemap.

```
public IEnumerable<Tile<T>> ValidNeighbours =>
{
get
{
for (int i = 1; i < 9; i++)
{
var tile = this.Neighbour(Extensions.DirectionDeltas[i]);
if (tile.IsValid)
yield return tile;
}
}
}
```

A simple enough change.

There are more things we can do with our `Direction`

type. What I have found useful for path-finding is to be able to know what directions are open, and which are blocked when moving from tile to tile.

For this purpose we could keep a list of our `Direction`

type above for each tile, but I find it nicer to create an actual type representing *a combination of directions*.

**To keep things light we can simply use another enum, however this time instead of using consecutive values, we will use only powers of two as values.**

That allows us to use bit-wise unions and intersections to represent and work with combinations of multiple directions.

```
[Flags]
enum Directions : byte
{
None = 0,
Right = 1 << (Direction.Right - 1),
UpRight = 1 << (Direction.UpRight - 1),
Up = 1 << (Direction.Up - 1),
UpLeft = 1 << (Direction.UpLeft - 1),
Left = 1 << (Direction.Left - 1),
DownLeft = 1 << (Direction.DownLeft - 1),
Down = 1 << (Direction.Down - 1),
DownRight = 1 << (Direction.DownRight - 1),
All = Right | UpRight | Up | UpLeft | Left | DownLeft | Down | DownRight,
}
```

Note how we make use of the existing `Direction`

type and the binary shift operator `<<`

to make sure the values of our distinct directions are correct.

Further, this well defined conversion from `Direction`

to `Directions`

allows us to easily check if one is contained in the other as follows.

```
public static bool Includes(this Directions directions, Direction direction)
{
return directions.HasFlag(direction.toDirections());
}
private static Directions toDirections(this Direction direction)
{
return (Directions)(1 << ((int) direction - 1));
}
```

Note how we use the same bit manipulating formula to convert the value as when initialising them above.

Further, we can also add and remove individual directions from a `Directions`

value.

```
public static Directions And(this Directions directions, Direction direction)
{
return directions | direction.toDirections();
}
public static Directions Except(this Directions directions, Direction direction)
{
return directions & ~direction.toDirections();
}
```

Note how most of this comes down to simple bit-wise operators and manipulation.

Of course, the purpose of our `Directions`

type was to use it as a sort of collection of directions. Let us implement the enumeration of the type.

Unfortunately, there is no easy to way to extract the contained directions directly, however we can loop over the few directions we have and check if each of them is included. If it is, we return it.

```
private static readonly Direction[] directions =
{
Direction.Right,
Direction.UpRight,
Direction.Up,
Direction.UpLeft,
Direction.Left,
Direction.DownLeft,
Direction.Down,
Direction.DownRight,
};
public static IEnumerable<Direction> Enumerate(this Directions directions)
{
foreach (var direction in Extensions.directions)
{
if (directions.Includes(direction))
yield return;
}
}
```

While we are thinking of the type as a collection, or more precisely a set (it does not allow for duplicate elements), we can of course also implement basic set operators and similar checks.

Here are some that I came up with, I am sure more are possible.

```
public static bool Any(this Directions direction)
{
return direction != Rectangular.Directions.None;
}
public static bool Any(this Directions direction, Directions match)
{
return direction.Intersect(match) != Rectangular.Directions.None;
}
public static bool All(this Directions direction)
{
return direction == Rectangular.Directions.All;
}
public static bool All(this Directions direction, Directions match)
{
return direction.HasFlag(match);
}
public static Directions Union(this Directions directions, Directions directions2)
{
return directions | directions2;
}
public static Directions Except(this Directions directions, Directions directions2)
{
return directions & ~directions2;
}
public static Directions Intersect(this Directions directions, Directions directions2)
{
return directions & directions2;
}
```

Note how all of these are implemented using simple bit-wise operators which makes them very efficient, especially compared to possible implementation using actual lists or other collections of `Direction`

.

For a commented version of these and other operations, feel free to check the full implementation on GitHub.

Starting from wanting to enumerate the tiles neighbouring another one, we designed and implemented simple binary types representing individual and sets of directions respectively.

Using specialised types allows us to work with directions effortlessly, while the implementation as simple enumerators gives us great performance.

*If you found this interesting, make sure to share the post on your favourite social media.*

Make sure to check back next week when we will take a look at coordinate systems and how to embed our tilemap inside our game world.

Enjoy the pixels!

The post Taking steps and other useful tilemap helpers appeared first on GameDev<T>.

]]>The post Writing a generic tilemap class appeared first on GameDev<T>.

]]>

**Generics is a powerful feature of modern programming languages. It allows us to write code once, but execute it for a number of different cases**, or use it in different ways, without having to copy-paste it, or write conversion code between cases.

This is especially true with collections. From typed arrays, to lists, dictionaries and sequence queries, generics help us consider all possible kinds of elements in our collections.

**We can consider a tilemap a collection of tiles**. In a specific game, each tile may contain any kind of information, from literal tile-drawing information to lists of contained objects and more.

This is a clear case for which using generics provides us with a modular implementation that we can use and reuse for different games with different kinds of tiles.

In the simplest case, we could use a two dimensional array as a tilemap:

```
Tile[,] tilemap;
```

While this works, it is not a very flexible solution, and exposing arrays to large parts of our code like that is ugly and potentially unsafe.

Instead, **let us create a wrapper class** that we can further extend to add more tilemap related logic in the future.

For a simple implementation we need a backing array, properties like *width* and *height*, as well as a way to retrieve and change individual tiles. For that we can use indexers.

```
class Tilemap<T>
{
private readonly T[,] tilemap;
public int Width { get; }
public int Height { get; }
public Tilemap(int width, int height)
{
this.Width = width;
this.Height = height;
this.tilemap = new T[width, height];
}
public T this[int x, int y]
{
get { return this.tilemap[x, y]; }
set { this.tilemap[x, y] = value; }
}
}
```

So far so good.

As we said above, our tilemap really is a collection of tiles. That means **we can implement interfaces like IEnumerable<T> to be able iterate over all tiles**.

Since we also know the number of elements in the tilemap, we further could fulfil part of the contract for `ICollection<T>`

, however since it makes no sense to speak of `Add`

or `Remove`

operations for a tilemap, it makes more sense to inherit from `IReadOnlyCollection<T>`

instead.

For this interface, we need to add the following members.

```
public int Count => this.Width * this.Height;
public IEnumerator<T> GetEnumerator()
{
for (int y = 0; y < this.Height; y++)
for (int x = 0; x < this.Width; x++)
{
yield return this[x, y];
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
```

As you can see, the enumeration is very straight forward. We simple use a nested loop to iterate the entire array, and return all elements.

*Note how the outer loop iterates over rows, while the inner iterates columns. This improves the methods efficiency by increasing memory locality such that we return elements in exactly the same order they are stored in memory in the array.*

A times, I wanted to enumerate a tilemap but next to getting a list of unidentifiable tiles, I also would have liked to know where each of these tiles is located in the tilemap.

Similarly, **it can be very helpful to store a reference to a tile**. Since the actual tiles of a tilemap may change however, it may be better to **store a reference to a position in the tilemap, instead of to the tile itself**. With that reference, we can retrieve the current tile at that location whenever needed.

For both of these purposes, we can create a simple wrapper structure representing a reference to a tile in our generic tilemap.

```
struct Tile<T>
{
private readonly Tilemap<T> tilemap;
public int X { get; }
public int Y { get; }
public Tile(Tilemap<T> tilemap, int x, int y) : this()
{
this.tilemap = tilemap;
this.X = x;
this.Y = y;
}
public T Value
{
get { return this.tilemap[this.X, this.Y]; }
}
}
```

With this type in place, we can make our tilemap class inherit `IReadOnlyCollection<Tile<T>>`

instead, and change our enumerating method as follows.

```
public IEnumerator<Tile<T>> GetEnumerator()
{
for (int y = 0; y < this.Height; y++)
for (int x = 0; x < this.Width; x++)
{
yield return new Tile<T>(this, x, y);
}
}
```

Further, we can create our own values of `Tile<T>`

at any point to refer to tiles in the tilemap, and keep these references in our other types. For example, a game object may want to know which tile of the tilemap it is in. With this wrapper type, it can store a reference to that tile, which is aware of its own position as well.

**I use a structure, instead of a class, to implement the Tile<T> wrapper.** While this is not necessary for any particular purpose, it enforces thinking of the type as a value: a reference or ‘pointer’ to a location on the tilemap, instead of any object itself.

Once we start using this type more and more to traverse the tilemap, we will see how using a class would mean many unnecessary object creations. **Using a value type for such small immutable types can improve performance and comes with no other drawbacks.**

Above we implemented a simple tilemap wrapper class, which uses a two dimensional array as storage for its tiles. This gives us much control over the underlying collection and makes sure the raw array is not exposed to the rest of our game.

Further we created a reference-structure to point at particular tile locations in the tilemap. This helps is keep track of positions on the tilemap, even if the tiles themselves might change.

*If this has been interesting to you, make sure to share this post on your favourite social media.*

Over the coming weeks I will be publishing further posts building on the code here, to highlight some of the many ways in which tilemaps can make our lives easier.

Enjoy the pixels!

The post Writing a generic tilemap class appeared first on GameDev<T>.

]]>The post Angular type-safe physical units appeared first on GameDev<T>.

]]>**Today we will look at how to implement the types necessary to also gain the advantages of type-safety when it comes to the rotation and orientation of an object.**

We will consider only the two dimensional case, since it is relatively straight forward. However, a similar approach could be taken in three dimensions as well, though it would significantly complicate the mathematics.

When discussing our implementation of two and higher dimensional types I made the case that despite the two having the same unit, it makes sense to split the concepts of absolute position, and relative difference between positions into two different types.

It makes sense to do the same when it comes to angles and orientations, and in fact the distinction may be even clearer here.

**Each object we can rotate in two dimensions clearly has a property representing its orientation** – the *absolute* direction in which it is facing. Instead of being infinite like a vector space, **this space is periodic** (with a period of 360 degrees), so we want to use a type that enforces this property automatically without us having to thing about it.

A *relative* angle on the other hand is a proper one dimensional vector space that can exceed the boundaries of the periodic angle space.

Consider how a value could represent the angular movement (i.e. rotation) of an object over the last 10 seconds. Since an object could have easily spun around two times in that time interval, the relative angle difference is in this interpretation 720 degrees.

This concept makes even more sense when we extrapolate it to angular velocity and acceleration further on: Clearly an object can spin so fast that its angular velocity exceeds 360 degrees/second. However, I am getting ahead of myself.

As it happens, I have discussed a possible implementation for exactly these two types: `Direction2`

and `Angle`

. **The implementation of Direction2 uses a backing integer and exploits the overflow behaviour of integer arithmetic** to naturally exhibit the periodic nature of a proper direction type at no additional cost – and with very fine and evenly distributed accuracy of representation, a fact not to be underestimated.

It may at first be unclear why we would use the two already implemented types. **Our goal here is to achieve type-safety of physical quantities.** The above types however are merely mathematical representations and have no actual physical unit associated with them. Contrary to this, our *speed* type for example used the unit of *distance/time*.

**Angles are a special case.** Depending on the definition, an Angle can be seen as the percentage or the full circle that it spans, or as the length of the arc, compared to the radius.

Note how both the arc and radius would be measured with the same distance unit. Therefore, the unit of angles is *distance/distance*. It is a *dimensionless* unit.

This means that we might as well use the same types for our purposes here, instead of reimplementing them entirely.

More importantly, the types as they are do not come with any operations we would like to catch as invalid (like most implementations of Vector2 types for example).

While being a dimensionless unit, of course angles do not actually have no dimension in the vector sense. They form one dimensional spaces as outlined above.

Having settled the differences between absolute directions and relative angles, we should add the additional types we need in order to work with the original types in our physical framework.

Similar as with the types handling locations and movement, we will want to add types representing the speed and acceleration of rotation: `AngularVelocity`

and `AngularAcceleration`

.

As explained above, **these form simple one dimensional vector spaces** with no further constraints and are as such easily implemented with a backing floating point value.

Like `Angle`

itself, they thus also have the associated vector space operations of addition, subtraction and scaling.

Additionally, **the types interact through integration and differentiation**, i.e. multiplication with or dividing by a time span.

The full list of operations we will have to implement is as follows.

```
// vector space types, AngularVelocity and AngularAcceleration
// at the exactly of AngularVelocity
angularVelocity + angularVelocity = angularVelocity
angularVelocity - angularVelocity = angularVelocity
angularVelocity * scaler = angularVelocity
// integration
angularVelocity * timespan = angle
angularAcceleration * timespan = angularVelocity
// differentiation
angle / timespan = angularVelocity
angularVelocity / timespan = angularAcceleration
```

Of course there are a few more operations we can add, but these form the basics that allow us to use these types instead of simple floating point numbers to get a type-safe representation for our angular movement.

For the full list of sensible operations see my full implementation, as well as the post on `Direction2`

and `Angle`

.

`Direction2`

There is another interesting set of interesting interactions that are are both plausible and physically well defined, so that we could add them to our list of operations.

These interactions rely on how `Direction2`

, **despite being a wrapper around a single value only makes sense in a two dimensional space**.

By combining it with a one dimensional physical type, we can construct a directed value of the same type, but in the two dimensional plane.

For example, given a direction and a speed, we could construct a two dimensional velocity that corresponds movement in that direction and that speed.

The same operations exists for each of out spacial unit types as follows.

```
direction2 * unit = difference2
direction2 * speed = velocity2
direction2 * acceleration = acceleration2
```

Whether it is a good idea to implement these operations using the multiplication operator may be a matter of personal taste.

Personally I like to be able to write code as follows.

```
Acceleration2 acceleration = this.facingDirection * this.forwardAcceleration;
```

I think this usage of the operator is clear enough, and much less cumbersome than using a method or constructor instead. Further I consider it clear in meaning and not ambiguous despite not being exactly mathematically rigorous – however I am curious to see if others agree.

Today we saw how we can implement type-safe representations of directions, as well as relative angles and angular velocities and accelerations. This completes this mini series on type-safe representations of physical types for two dimensional games.

*I hope you found this interesting, and if you did consider sharing this post on your favourite social media.*

Enjoy the pixels!

The post Angular type-safe physical units appeared first on GameDev<T>.

]]>The post Extending type-safe physical values to multiple dimensions appeared first on GameDev<T>.

]]>Today we will expand these ideas to more than one dimension, with the example of two dimensional types.

The types we implemented in the last post are `Unit`

, `Speed`

, `Acceleration`

, `Timespan`

and `Instant`

.

Apart from `Instant`

these all form **one-dimensional vector spaces**. `Instant`

is special since its semantic meaning is different from the other. By splitting it from `Timespan`

we split the concepts of absolute and relative time. While this is not necessary to make the mathematics work out, it is an additional type check the compiler can do for us, since the two should not be used interchangeably.

We saw that we could have done the same with `Unit`

, splitting it into an absolute position, and a relative difference. In fact, the same could be done with `Speed`

and `Acceleration`

as well. However, we did and are not doing so, since the usage for these extra types would be limited.

I argue that the effort and complication of having so many extra types does not outweigh the advantages gained. That being said, I would be curious to hear arguments for splitting these types.

When adding further dimensions, what we mean is adding spatial dimensions. We are perfectly happy with sticking with a single dimension of time here.

That means that our time related types are just fine the way they are.

What we want to look at is the remaining types. We want to represent the same concepts in two dimensions.

So let us start with the following list of types: `Unit2`

, `Speed2`

, `Acceleration2`

.

This works, however, the names of `Unit2`

and `Speed2`

are somewhat awkward. Let us rename the latter to `Velocity2`

.

Unlike in the one-dimensional set of types, the concepts of *position* and *difference between positions* are quite different in two dimensions. I argue that this is a difference worth splitting the `Unit2`

type over. **In an actual game or application we will deal with a lot of absolute positions, but also with a lot of differences between them.** We want to make sure that the two cannot be confused.

Let us call these new types `Position2`

and `Difference2`

.

Our full list of new types is now `Position2`

, `Difference2`

, `Velocity2`

, and `Acceleration2`

.

Apart from `Position2`

with its special absolute nature (just like `Instant`

) **these are again vector fields, just in two dimensions**.

That means we can apply all the usual operations like addition, subtraction and scaling.

**The interaction with Position2 is more limited.** We can merely subtract two of them to receive the difference between them, or we can add a

`Difference2`

to receive a new position.When we add our `Timespan`

type to the mix, we can however also **use multiplication with and division by it to integrate and differentiate** between the other types.

The full list of operations that we define is as follows.

```
// Vector field operations for difference2, velocity2 and acceleration2
// (example: difference2)
difference2 + difference2 = difference2
difference2 - difference2 = difference2
difference2 * scalar = difference2
difference2 / scalar = difference2
// interactions with position2
position2 - position2 = difference2
position2 + difference2 = position2
difference2 - difference2 = position2
// integration
acceleration2 * timespan = velocity2
velocity2 * timespan = difference2
// differentiation
difference2 / timespan = velocity2
velocity2 / timespan - acceleartion2
```

There are a couple of other operations we could add, but these are all we need in most cases. They allow us to do all the usual operations of calculating difference between different objects, apply forces as accelerations, and integrate velocities to calculate movement per frame.

For a full implementation feel free to checkout the same classes discussed here on GitHub.

Today we took a look at how to extend the idea of representing physical quantities with concrete type-safe types to two dimensions.

*If you found this post interesting, make sure to share it on your favourite social media.*

Next week we will take a look at how we can further work with these types and represent the orientation and rotations of our game objects as well.

Until then, make sure to leave a message below if you have any questions or comments.

Enjoy the pixels!

The post Extending type-safe physical values to multiple dimensions appeared first on GameDev<T>.

]]>