简体   繁体   中英

How can I incorporate the camera's position into this algorithm to calculate a sprite's position on the screen?

I'm working on a 2D rendering system in 3D space, for practice. The sprites are 2D, but they're rendered in 3D space. The "camera" can move in 3D space and turn 360 degrees horizontally. I'm having trouble figuring out the right formula to calculate, based on the position/rotation of the camera and the position of the assets, where they should exist on the screen.

What I have is like this:

chunk.assets.forEach(asset => {
    let x = Math.round(
      asset.coords.x * Math.cos(angle) - asset.coords.y * Math.sin(angle)
    );
    let y = Math.round(
      asset.coords.y * Math.cos(angle) + asset.coords.x * Math.sin(angle)
    );
    if (!depthMap[y]) {
      depthMap[y] = [];
    }
    depthMap[y].push(asset);
});

But this does not take into account the camera's (player's) position (stored at player.coords.x, player.coords.y ), only the angle the camera/player is facing ( angle ). So right now the camera can't move. Note: Depth map is just storing the assets in order so the renderer knows which order to render the sprites so things appear in the right order based on which is closer to the player/camera.

How can I incorporate the camera's position into this algorithm?

Some assumptions:

If the camera and the sprite are at the same position, the sprite will be rendered at 0|0.

Wether the camera moves left or the sprite moves right does not matter.

From that we can conclude that only the relative position matters, and that can be easily calculated (by subtracting both positions).

 let x = Math.round(
  (asset.coords.x - player.coords.x) * Math.cos(angle) - (asset.coords.y - player coords.y) * Math.sin(angle)
);
let y = Math.round(
  (asset.coords.y - player.coords.y) * Math.cos(angle) + (asset.coords.x - player.coords.x) * Math.sin(angle)
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM