I'm working on an assignment that I need to move a sphere around the screen with the keyboard arrows. I got the movements working and all that. But I'm drawing a blank on an "if" statement to prevent the image from going off the screen when the edges are reached.

if (KEY_DOWN(VK_DOWN))
	{
		d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
		rect2.top = rect2.top + 1;
		rect2.bottom = rect2.bottom + 1;

		if (rect2.bottom > SCREEN_HEIGHT)
		{
			rect2.bottom = - 1;
		}
	}

By the looks of things (I am guessing a bit -- but there is very little code to go on) , you have a rectangle of with top/bottom cordinates.

Then you add 1 to top and bottom but if you reach the bottom of the screen the bottom only is reset. I guess that you draw with a routine that probabily use the top + size so it doesn't work.

Maybe this will work:

if (KEY_DOWN(VK_DOWN))
{
    d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
   if (rect2.bottom<SCREEN_HEIGHT-1)
      { 
         rect2.top = rect2.top + 1;
         rect2.bottom = rect2.bottom + 1;
      }
}

I figured it out, thanks though. I had to use the screen height & widith for bottom & right (since their initial value is not 0), when that condition is met the value for those go in the opposite direction causing it to stop moving in that direction. Then for top & left I stated that if top or left equalled 0 then their values changed the same way the others did, which prevented it from going further in that direction.

if (KEY_DOWN(VK_DOWN))
	{
		d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
		rect2.top = rect2.top + 1;
		rect2.bottom = rect2.bottom + 1;

		if (rect2.bottom > SCREEN_HEIGHT)
		{
			rect2.top = rect2.top - 1;
			rect2.bottom = rect2.bottom - 1;
		}
	}
	if(KEY_DOWN(VK_UP))
	{
		d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
		rect2.top = rect2.top - 1;
		rect2.bottom = rect2.bottom - 1;

		if (rect2.top == 0)
		{
			rect2.top = rect2.top + 1;
			rect2.bottom = rect2.bottom + 1;
		}
	}
	if(KEY_DOWN(VK_RIGHT))
	{
		d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
		rect2.left = rect2.left + 1;
		rect2.right = rect2.right + 1;

		if(rect2.right > SCREEN_WIDTH)
		{
			rect2.right = rect2.right - 1;
			rect2.left = rect2.left - 1;
		}
	}
	if(KEY_DOWN(VK_LEFT))
	{
		d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
		rect2.left = rect2.left - 1;
		rect2.right = rect2.right - 1;

		if(rect2.left == 0)
		{
			rect2.left = rect2.left + 1;
			rect2.right = rect2.right + 1;
		}
	}
This question has already been answered. Start a new discussion instead.