hecrj / coffee

An opinionated 2D game engine for Rust
https://docs.rs/coffee
MIT License
1.08k stars 55 forks source link

Add project/unproject methods to `Transformation`. #117

Closed JohnDoneth closed 2 years ago

JohnDoneth commented 4 years ago

Motivation

I needed a way to project camera coordinates to world coordinates to be able to "pick" tiles using the mouse in a tile based game with a moving camera; In order to do so I needed to project the screen space coordinates into the world using the current Transformation.

Solution

Add the following methods to coffee::graphics::Transformation.

pub fn project(&self, point: Point) -> Point;

pub fn unproject(&self, point: Point) -> Point;

Further Work / Possible Improvements

hecrj commented 4 years ago

Test is failing because of https://github.com/rust-lang/log/issues/372.

Apparently, there have been two patch releases of the log crate with breaking changes in a day... I hope they yank the last release soon.

hecrj commented 4 years ago

Thanks for this! Looks good, just a small detail.

JohnDoneth commented 4 years ago

I believe this should be good to go. Please feel free to let me know if you would like to see any additional changes.

hecrj commented 4 years ago

I wonder... Shouldn't unproject and project swap names? I think projecting should perform simple multiplication.

Maybe, instead of using methods, we could simply implement std::ops::Mul<Point> for Transformation and add a Transformation::inverse(&self) -> Option<Transformation>. I think that would be more explicit for users.

JohnDoneth commented 4 years ago

Yeah you're probably correct about the name swap, I was confused myself with which was which. The logic I was following was that the camera "projects" into the world, so it would make sense to go from screen-coordinates to world-coordinates. But then I suppose it's the opposite for 3D graphics, where you have a projection matrix to go from the 3D-world-coordinates to screen-coordinates.

I like the proposed change and agree that that API would be more explicit, I'll get right on it when I get a chance.