1
General / Re: Spawning some bullets
« on: September 11, 2014, 03:48:48 am »So I have an idea on how I want to spawn bullets for this space-shooter I'm making. But the problem is, I have an option to rotate the shooter (setRotation + or -), and there's a specific bullet hole where the bullets are supposed to come out of.
I'm having trouble figuring out how to trace that bullet hole and set the bullet's position to that same spot even when the sprite rotates.
Can you guys please help me?
Based on your description, I read your problem as follows:
You have a shooter, with a position and a rotation.
You want to create bullets at a position on the shooter that changes with it's rotation.
You can do that quite simply with a Rotation Matrix, which is quite simple for 2D rotations. For example, if your gun's barrel is at {10, 20} relative to the centre of the shooter sprite, then you can calculate where the bullet should be created with:
float rotation = shooter.getRotation();
sf::Vector2f barrel(10.f, 20.f);
sf::Vector2f rotated;
// Rotate barrel around {0,0}.
rotated.x = barrel.x * cos(rotation) - barrel.y * sin(rotation);
rotated.y = barrel.x * sin(rotation) + barrel.y * cos(rotation);
// "barrel" is relative to the center of the sprite, we must add it to the position to get the final coordinates.
sf::Vector2f barrelWorld = shooter.getPosition() + rotated;
sf::Vector2f barrel(10.f, 20.f);
sf::Vector2f rotated;
// Rotate barrel around {0,0}.
rotated.x = barrel.x * cos(rotation) - barrel.y * sin(rotation);
rotated.y = barrel.x * sin(rotation) + barrel.y * cos(rotation);
// "barrel" is relative to the center of the sprite, we must add it to the position to get the final coordinates.
sf::Vector2f barrelWorld = shooter.getPosition() + rotated;
disclaimer: I haven't tried to run this code.