dimanche 18 février 2018

C++ SFML laser reflecting to the wrong way sometimes

I'm working on reflections against rotated objects. I'm using OBB collision detection, and this works. My reflection is working half. As you can see in the image below, you see that laser 1 is correct, but laser 2 isn't.

Laser 1 and 2

Somehow the dotproduct of laser 2 is wrong. Laser 1 dotproduct value is lower than 0 and laser 2 dotproduct is higher than 0. I can't figure out what's wrong with my code.

This is my code:

                // Get sprite points
                sf::Transform trans = testBlok.getTransform();
                sf::IntRect local = testBlok.getTextureRect();
                sf::Vector2f Points0 = trans.transformPoint(0.f, 0.f);
                sf::Vector2f Points1 = trans.transformPoint(local.width, 0.f);

                // Get normal vector of the sprite
                sf::Vector2f NormalHit;
                NormalHit.x = Points0.x - Points1.x;
                NormalHit.y = Points1.y - Points0.y;

                // Normalize
                float NormalLength = 1 / sqrt(NormalHit.x * NormalHit.x + NormalHit.y * NormalHit.y);
                NormalHit.x /= NormalLength;
                NormalHit.y /= NormalLength;

                // Reflected velocity
                sf::Vector2f u = (-2 * (lasers[i]->laserVelocity.x * NormalHit.x + lasers[i]->laserVelocity.y * NormalHit.y) * NormalHit + lasers[i]->laserVelocity);

                // Normalize reflected velocity
                float ULength = sqrt(u.x * u.x + u.y * u.y);
                u.x /= ULength;
                u.y /= ULength;

                // Get the angle for rotating the laser
                float radians = atan(u.y/u.x);
                float degrees = radians * (180.0/3.141592653589793238463);

                // Set new rotation and velocity
                lasers[i]->Line.setRotation(degrees + 90.f);
                lasers[i]->laserVelocity = u * LASER_MOVEMENT_SPEED;

Do you know what the problem is?





Aucun commentaire:

Enregistrer un commentaire