reddead
reddead

Reputation: 320

worldToScreen() - How does it work?

I am reading an android tutorial for game development that explains how to convert in-game coordinates to actual pixels. Simple enough. This is done via function worldToScreen() as follows:

public Rect worldToScreen(float objectX, float objectY, float objectWidth, float objectHeight){

        int left = (int) (screenCentreX - ((currentViewportWorldCentre.x - objectX) * pixelsPerMetreX));
        int top = (int) (screenCentreY - ((currentViewportWorldCentre.y - objectY) * pixelsPerMetreY));
        int right = (int) (left + (objectWidth * pixelsPerMetreX));
        int bottom = (int) (top + (objectHeight * pixelsPerMetreY));

        convertedRect.set(left, top, right, bottom);

        return convertedRect;
    }

It seems to return a rectangle object containing the four points that a square object would occupy.

  1. Why does it use a square?
  2. Why is it substracting top/left and adding bottom/right?

A thorough explanation will be much appreciated.

Upvotes: 1

Views: 521

Answers (1)

Marcello Davi
Marcello Davi

Reputation: 433

Answer to question 1

He's using a rectangle probably because it's a simple geometry object that is already implemented in Java and in most gaming libraries, like the one you are using (i can see he's using the Rect class).

Rectangle is also a common solution in 2D games when you want to implement simple collision detection for example.

Answer to question 2

You ask why he's adding bottom and right... But i can only see that he's adding top and left. He's doing that because the y axis goes from up to down, and the x axis goes from left to right.

So to get the bottom point you have to add the y coordinate of the top point to the height of the rectangle.

Same for the right point, you have to add the x coordinate of the left point to the width of the rectangle.

In the hope that my Paint skills can come useful i made a drawing that probably will help you understand: enter image description here

To make the drawing and my answer even more clear:

top + height = bottom

left + width = right

PS: "he" is the guy who made the tutorial that you're following.

Upvotes: 2

Related Questions