Search code examples
c#imageimage-processingxnacollision-detection

Handling background based per pixel collision with different screen resolutions and image stretching


I've been building a game engine in C# using XNA as my first foray into programming, and I want to use this to more fully understand the problems that I need to know how to solve.

The portion of the engine I am currently working on is the collision detection. The mode I'm working on is an image based, proactive collision system.

The character has a position (XNA Rectangle), the background is 2 textures, and the character has a Vector2 motion property. 1 is the display texture, and the other is a two color map of collision zones in the first texture. I display texture 1, and load texture 2 into an array of Color[] using the texture's GetData routine whenever the background is loaded. The input parsing routine does not change the position directly, it adds to the motion property.

So, each update: Check the input parser, and add to the motion Vector2. Compare the player's position.X/Y along each surface's position.Width/Height to the direction the motion would take it. If the motion would take it to a collision zone(as detected by comparison with the Color[] array), the motion is zeroed out(except for a gravity subroutine), and no movement is done in that particular direction.

This allows me to not halt all motion, just like in games like super mario, where jumping into the side of a block would not end your Y axis motion.

Now, my problem (that description got out of control quickly)...

How should I handle different resolutions? I do not understand how to scale an image to fill the desired area, then have it in a format that I can use to pull a GetData? I do not want to have the game load different background collision detectors for each resolution. I feel that's a job for coding, not for art/design.


Solution

  • Use a proportional approach...

    Suppose your background texture has a size (Wbk, Hbk) and you draw it to a viewport with size (Wvp, Hvp) and an offst (Xvp, Yvp).

    The viewport is a rectangle inside your screen where you draw the background.

    Now you want to get the right coords (Xc,Yc) inside background texture for a screen position (Xs,Ys) where you draw the sprite...

    Then you need to calculate the multiplication of the background texture size by the coords relative to your viewport divided by the viewport size.

       Xc= Wbk * (Xs-Xvp)/Wvp;
       Yc= Hbk * (Ys-Yvp)/Hvp;