I'm working with C++ SFML and I'm trying to reflect a laser against a wall, but the new velocity is always wrong. I don't know what to do and I can't find an solution. Can someone help me?
Shoot laser
const float PI = 3.14159265359;
float rotation = heroCharacter->heroHeadSprite.getRotation();
sf::Vector2f position = heroCharacter->heroHeadSprite.getPosition();
// Set velocity
sf::Vector2f velocity;
velocity.x = cos(rotation * (PI / 180)) * LASER_MOVEMENT_SPEED;
velocity.y = sin(rotation * (PI / 180)) * LASER_MOVEMENT_SPEED;
std::cout << "Start Velocity " << velocity.x << " " << velocity.y << std::endl;
// Character rotated, so change laser velocity to minus
if (heroCharacter->isCurrentDirectionRight == false)
{
velocity = -velocity;
}
xi and yi are the values of the intersection place.
Reflect laser
sf::Vector2f normal(-4 * xi, -yi);
// normalize vector length
float normalLength = sqrt((-4 * xi) * (-4 * xi) + (-yi) * (-yi));
normal.x /= normalLength;
normal.y /= normalLength;
// current direction of the ray
sf::Vector2f direction(xi - lasers[i]->laserVelocity.x, yi - lasers[i]->laserVelocity.y);
sf::Vector2f reflect = (-2 * (direction.x * normal.x + direction.y * normal.y) * normal + direction);
float slope = reflect.y / reflect.x;
sf::Vector2f to;
to.x = (4*lasers[i]->laserVelocity.x - slope*slope*lasers[i]->laserVelocity.x + 2*slope*lasers[i]->laserVelocity.y) / (-4 - slope*slope);
to.y = slope * (to.x - lasers[i]->laserVelocity.x) + lasers[i]->laserVelocity.y;
std::cout << "To X " << to.x << std::endl;
std::cout << "To Y " << to.y << std::endl;
lasers[i]->laserVelocity = to;
lasers[i]->test = true;
Aucun commentaire:
Enregistrer un commentaire