faiface / pixel

A hand-crafted 2D game library in Go
MIT License
4.43k stars 244 forks source link

[Question] Flipping Y-Axis #35

Closed silbinarywolf closed 7 years ago

silbinarywolf commented 7 years ago

How do I go about flipping the Y-axis so that:

I'd like the code I'm writing to work with however the user has setup their own window too, so being able to set it back would be great.

Aiming to build a little integrated map editor.

faiface commented 7 years ago

All you need to do is to set up a correct matrix. So, let's build it up, step-by-step. We start with the identity matrix.

flipY := pixel.IM

Now, we want to flip the Y axis. That can be achieved with scaling by a negative number.

flipY := pixel.IM.ScaledXY(pixel.V(1, -1))

The origin is still at the bottom-left though. We need to move it up, to the top-left.

flipY := pixel.IM.ScaledXY(pixel.V(1, -1)).Moved(pixel.V(0, win.Bounds().H()))

And that's it. Now, if you want to use a different matrix for camera and you want it to behave as in the world with the flipped axis, all you need to do it this:

win.SetMatrix(cam.Chained(flipY))

Note, that this will cause your sprites and text be flipped. You can flip them back with their own matrices when drawing them.

sprite.Draw(win, pixel.IM.ScaledXY(pixel.V(1, -1)).Chained(myNormalMatrix))

I might have messed up the order somewhere, needs to be tested.

silbinarywolf commented 7 years ago

Looks like "pixel.IM.ScaledXY" takes two arguments. I also don't see much point in flipping manipulating the window matrix if it's just going to require more transformations per sprite I draw...

(FYI, reason for wanting top-left and flipping Y is because I'm used to using Game Maker Studio 2)

faiface commented 7 years ago

Yep, I forgot that ScaledXY also takes an around argument, which specifies the point around which you're going to scale it.

Btw, setting the matrix of a window doesn't increase the number of operations per sprite. Creating an individual matrix for each sprite obviously does, but it shouldn't be too bad.

If this is a real feature you want to have, this is the way to do it. If it's just about what you're used to, I'd suggest getting used to Pixel's coordinate system ;)

faiface commented 7 years ago

I guess the question was answered, so I'm closing. Feel free to reopen if not ;)