Thursday, December 5, 2013

Unity Tutorial: Find the edges of the screen.

Recently I have been working on a 2D project in Unity. I came across a problem where I wanted the player to move a square on screen but not have the square disappear off the edges of the screen. It took a while to figure it out but eventually I managed to do it. I'm posting here in case anyone else come across this problem.

In this project you should set up a camera and an object you want the player to be able to move. Create a script and attach it to the object you want to move and open the script.

The first this we do is add the following line to the update method.
Here we pass in the transform of the moving object. ScreenPosition will contain values for the x, y, and z position of the object. These values will range from between 0 to 1. I found it easier to work with pixels so that's what we will convert it to now. Next we need to find the width and height, in pixels, of the screen. That's all the data we need to make sure the object always stays on screen. The next thing you need to do is check player input and then if the objects transform.position + movementSpeed is less that maxX/maxY and greater that 0.

Monday, December 2, 2013

Find the maximum screen resolution in Monogame or XNA

There are many ways to find the max screen resolution in XNA, however many of these do not work with Monogame. After some experimentation I have managed to find one that does.

The lines of code above should give you the actual width and height of the screen in pixels.