Question

This is pretty much a code-agnostic question. I am not sure if this the correct term, but I am looking for the formula to do this.

Basically I have a rect "gateway" object in my game that transfers the player between the levels.

gateway In my case, I have two "gateway" rectangles, rect A is 1200 pixels wide, rect B is 330 pixels wide. (The reason the 2 rects have different widths is because of the other level's different scale factor)

When the "player" object collides with rect A, it should go to the next level and exit out from rect B but from a coordinate that is relevant to its entry (from rect A) but "normalized" to fit the size of rect B.

Was it helpful?

Solution

I believe what you are looking for is the ability to map the relative location of a value in first range to its respective position within another range.

Here is a C++ function that takes the floor and ceiling of two ranges and the input value in which you wish to map from range one to range two. There is an edge case where the function would divide by zero. If that case is detected, it returns a value in the middle of the out range.

inline float rangeMapFloat( float inRangeStart,
 float inRangeEnd,
 float outRangeStart,
 float outRangeEnd,
 float inValue ) 
{

    // Handle the zero edge case
    if ( inRangeStart == inRangeEnd  ) {
        return 0.50f * ( outRangeStart + outRangeEnd );
    }

    float outValue = inValue;

    outValue = outValue - inRangeStart;
    outValue = outValue / ( inRangeEnd - inRangeStart );
    outValue = outValue * ( outRangeEnd - outRangeStart );
    outValue = outValue + outRangeStart;

    return outValue;

} 

For example, if you have your larger rect being 0-1200 pixels wide and your smaller rect being 0-400 pixels wide with the player colliding with pixel 800 of the larger rect, then the function call would look as follows;

float teleportLocationWithinNewRect = rangeMapFloat( 0.0f, 1200.0f, 0.0f, 400.0f, 800.0f );

In this case 800.0f is 2/3 the width of the large rect, so the value returned will be 2/3 the value of 400.0f (~ 266.7f).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top