问题描述:

I searched and implemented things from this forum, it doesn't come out right.

What I'm trying to achieve is to calculate a spawnPoint for player bullets relative to his position and rotation.

The spawnPoint should be and his X + his width (the player is set to point to the right by default) and y + height/2 (to spawn from his center on the Y axis).

This is what I got from this forum:

this.bulletSpawn.x = (float)(this.position.x + this.width/2 + this.width * Math.cos(rotation));

this.bulletSpawn.y = (float)(this.position.y + this.height/2 + this.height/2 * Math.sin(rotation));

The rotation is in Radians. The this is the Player class.

Images showing what I expect to happen:

  • Original Position
  • Expected Behaviour

The red dot is the spawnPoint I'm trying to calculate knowing the player position and rotation.

The player Sprite is what rotates, and it rotates related to his center x and y, which is done with a lib, i do not have these variables. The entire arrow would be the player , the arrow direction is where the player is pointing at, and the red dot would be the bulletSpawn point (or the expected one)

Using the code I posted, the bullets seem to be spawning from somewhere else. Even at the beggining they have an offset and when I rotate the player the spawnPoint seems to be relative to a different origin than what I'm expecting.

This is the bullet position code:

position.x = holder.bulletSpawn.x - (float)(this.width/2 * holder.rotation);

position.y = holder.bulletSpawn.y - (float)(this.height/2 * holder.rotation);

This is inside the Bullet class. The position variable is a Vector2 of bullet, and holder is the player instance. This code is merely to give an offset for the bullet to spawn at the center of its own size

I added some fixes related to the comments, but the bullets still have a tiny offset that looks wrong at certain angles.

Basically the distance i want to get is the width of the player, and his center y which is height/2.

网友答案:

Let's initial position is X0, Y0, rotation is about center point CX, CY, and rotation angle is Theta. So new position after rotation is:

 NX = CX + (X0-CX) * Cos(Theta) - (Y0-CY) * Sin(Theta)
 NY = CY + (X0-CX) * Sin(Theta) + (Y0-CY) * Cos(Theta)

This equations describe affine transformation of rotation of arbitrary point about center point, and affine matrix is combination of translation, rotation, and back translation matrices.

About center CX, CY - you wrote

it rotates related to his x and y origin at his bottom left

About initial point coordinate - for bullet it seems to be

X + Width, Y + Height/2
相关阅读:
Top