Search code examples
c#drawingdirectx

Drawing directly in the game, not in the screen


I'm playing a game and I want to draw a line on it. I can't use Graphics.DrawLine because it takes the window/screen coordinates, not the game coordinates.

I want to draw a line from game's pos A to games's pos B. If I put those coordinates in DrawLine, it will take X's and Y's coordinates of the window/screen, not from the game.

In the image below as a example, I want to draw the blue line, but using DrawLine it will draw the grey line.

enter image description here

I want to draw even if the points were not visible in the screen, as I showed in this example. If I move the screen through the game's scenario, the line keeps static since the coordinates of the points A and B keep the same.

Is there a way to do it?


Solution

  • The point here is to convert the world coordinates into screen coordinates. For example, suppose I want to draw a line from point x = 100, y = 600 to point x = 700, y 600 in the world map and the left of my screen is at x = 300 and it's bottom is at y = 300 in world coordinates, then the drawing should start from x = -200, y = 300 to x = 400, y = 300 in screen coordinates which would finish the drawed line at the center of the screen, assuming it's resolution is 800x600.

    Since the screen moves in relation to the world scenario, the code for the world to screen method could be:

    static int[] WorldToScreen(int worldX, int worldY, int worldX2, int worldY2, int screenLeft, int screenBottom)
            {
                int screenX = worldX - screenLeft;
                int screenY = worldY - screenBottom;
    
                int screenX2 = worldX2 - screenLeft;
                int screenY2 = worldY2 - screenBottom;
    
                return new int[] { screenX, screenY, screenX2, screenY2 };
            }
    

    Now we just take these converted coordinates and draw on the screen using GDI, DirectX or whatever you want.

    PS: Screen (or camera) coordinates are usually related to the center of the screen. I used the edges here just for simplification.