# Torus World Collision Dection

I am looking for a collision detection solution for use when 2d screen wrapping. Specifically, when the image is split between the right and left side I can only detect a collision for a limited area.

For example, the program detects the collision when the rectangle intersects the circle in the first image. However, it doesn't in the second image. I am using the Rectangle.Instersects method to check for the collision in both cases.

I used the screen-wrapping solution at the following link: How to create a 2D region where sprites are automatically wrapped?

However, since I am not using the physics engine, I am not using the related solution at: How to create a very specific kind of joint in Farseer?

I am aware of the following question: https://stackoverflow.com/questions/8679304/wrapping-drawn-image-in-xna-4-0, and incorporated part of the code to reset the draw rectangle's position when wrapping for both sprites:

 // reset draw rectangle for wrapping
if (drawRectangle.X < -sprite.Width)
{
drawRectangle.X += parentWindowWidth;
}
if (drawRectangle.X > parentWindowWidth)
{
drawRectangle.X -= parentWindowWidth;
}
if (drawRectangle.Y < -sprite.Height)
{
drawRectangle.Y += parentWindowHeight;
}
if (drawRectangle.Y > parentWindowHeight)
{
drawRectangle.Y -= parentWindowHeight;
}


This post also says that I have to check for the collision in the two separate positions, but I am having trouble doing so.

Any suggestions?

## 1 Answer

I had to solve this issue a long time ago, and all I did was do:

• One normal collision check.
• One where I shifted everything up one "world-height" (aka screen height)
• Shift down
• Shift left one "world-width" (screen width)
• Shift right
• Up and Right
• Up and Left
• Down and Right
• Down and Left

eg:

if(x + width  > test.x && x < test.x + test.width &&
y + height > test.y && y < test.y + test.height)
{
Collide!
}
else if(x + width  > test.x + worldWidth && x < test.x + test.width + worldWidth &&
y + height > test.y && y < test.y + test.height)
{
Collide!
.... 7 more times


Seems cumbersome and inefficient, and it probably is, but it's the easiest & most straight-forward way to solve this issue.

Below, I've drawn your playable area in white, and the possible collision zones in other colours in the diagram below:

In this example, I have left the circle in place (x and y in example code), and compared it against your squiggle of colours in all 9 possible configurations listed above. As a visual demonstration, I've drawn all 9 possibilities.

This should get you pointed in the right direction.

Other torus-world tips I can provide are:

• You're going to need to detect when an object crosses these boundaries and draw the same thing up to 4 times if it's straddling a corner.
• Shortest paths (eg, Homing missiles) will need to compare all 9 routes to the target.