简体   繁体   中英

Calculating relative item positions based on camera position and rotation

For a 2d game, I have these concepts:

  • stage: container in which items and cameras are placed.
  • item: a visible entity, located on a certain point in the world, anchored from center.
  • camera: an invisible entity, used to generate relative images of world, located on a certain point in the world, anchored from center.

In the illustrations, you can see how they are related, and what the end result should be.

图片1图片2

Here is the code I have: (dumbed down to make it easier to read)

Note1: This is not happening on canvas, so I will not use canvas translation or rotation (and even then, I don't think it would make the problem any easier).

Note2: Item and camera positions are center coordinates.

var sin = Math.sin(rotationRad);
var cos = Math.cos(rotationRad);

var difX = item.x - camera.x;
var difY = item.y - camera.y;
var offsetX = camera.width / 2;
var offsetY = camera.height / 2;

var view.x = (cos * difX) - (sin * difY) + _Ax + _Bx;
var view.y = (sin * difX) + (cos * difY) + _Ay + _By;

This is supposed to calculate an items new position by:

  • calculating new position of item by rotating it around camera center
  • (_A*) adjusting item position by offsetting camera position
  • (_B*) adjusting item position by offsetting camera size

I tried several different solutions to use for _A* and _B* here, but none of them work.

What is the correct way to do this, and if possible, what is the explanation?

You first subtract new origin position from object position. You then rotate it by the inverse of the rotation. New origin can be camera position of top left corner of viewport. Of course if you know viewport center its top left corner is computed by subtracting half of its dimensions.

Like this:

var topLeft = Camera.Position - Camera.Size / 2;

var newPosition = Object.Position - topLeft;

newPosition = Rotate(newPosition, -camera.Angle);

Rotation is very simple:

rotatedX = x * cos(angle) - y * sin(angle)
rotatedY = y * cos(angle) + x * 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