Saturday, March 21, 2015

c++ - Shooting many bullets toward the mouse position


I try to shoot a bullet toward the mouse position by this code.


float deltaX = mousePosition.x - (aircraft.getPosition().x + aircraft.getLocalBounds().width / 2);

float deltaY = mousePosition.y - (aircraft.getPosition().y + aircraft.getLocalBounds().height / 2);
float angleRadian = (float)(std::atan2(deltaY, deltaX));
float angleDegree = (float)(angleRadian * 180 / PI);

It works fine with one bullet but when I add another one bullet to shoot together I use this code to specify start shooting point of each bullets.


sf::Vector2f offset1(aircraft.getPosition());
offset1.x += -10;//start shooting point first bullet.

sf::Vector2f offset2(aircraft.getPosition());
offset2.x += 10;//start shooting point second bullet.


this is a picture of this problem. enter image description here


When I rotate aircraft to picture 2 the bullets are not the same as the first picture.


How can I solve this problem?



Answer



This is rather easy using the buit-in transforms:


float hoffset = ...; // This is the horizontal offset for the gun

sf::Transform rotation;
rotation.rotate(angle); // This is essentially the ship's rotation


// This will get you the offsets relative to the ship's position
sf::Vector2f bulletOffsetLeft(rotation.transformPoint(-hoffset, 0.f));
sf::Vector2f bulletOffsetRight(rotation.transformPoint(hoffset, 0.f));

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...