Question

I have been trying to implement The second answer of this question

My variables are mainly named the same as in the link.

Here they calculate the bounce angle of a point on a rotated surface with normals, But I can't seem to do it, am I doing something wrong?

The value output I'm expecting is the new velocity after bouncing on the rotated line, currently my output is doing all crazy kind of things, bouncing to high, bouncing the other way and sometimes the right way but mostly ignoring the rotated angle of my line.

Here's my current Code:

Variables:

  • Top is the first point of my line
  • Right is the second point of my line
  • n is the normal
  • v is the velocity
  • dotv is n * v
  • dotn is n * n

Old Code:

sf::Vector2f n(-(top.y - right.y),(top.x - right.x));
sf::Vector2f dotv = sf::Vector2f(ball.getSpeed().x * n.x, ball.getSpeed().y * n.y);
sf::Vector2f dotn = sf::Vector2f(n.x*n.x,n.y*n.y);
sf::Vector2f u = sf::Vector2f(dotv.x/dotn.x,dotv.y/dotn.y);
u = sf::Vector2f(u.x*n.x,u.y*n.y);
sf::Vector2f w = ball.getSpeed() - u;
ball.setSpeed(sf::Vector2f((sf::Vector2f(w.x*0.5,w.y*0.5)-u)));

Edit:

New Code:

sf::Vector2f n(-(top.y - right.y),(top.x - right.x));
double dotv = ball.getSpeed().x*n.x + ball.getSpeed().y*n.y;
double dotn = n.x*n.x + n.y*n.y;
sf::Vector2f u = sf::Vector2f((dotv/dotn)*n.x, (dotv/dotn)*n.y);
sf::Vector2f w = ball.getSpeed() - u;
ball.setSpeed(sf::Vector2f(ball.getSpeed().x,ball.getSpeed().y) - w);

At first I made the mistake of calculating dotproducts as vectors this has been resolved, now it still gives me a strange output It fires my ball directly trough my object in the angle of the reversed normal

Any help would be greatly appreciated.

Was it helpful?

Solution

One problem I see is that you have dot products as vectors. A dot product results in a scalar (single value).

Also, to make your life a lot easier, you make functions for vector operations and even overload operators when appropriate. E.g. vector addition, subtraction. It's probably best to regular functions for dot product and cross product. Here are some examples of what I mean

class Vector2f
{
    // Member of Vector2f
    X& operator+=(const Vector2f& other)
    {
        x += other.x;
        y += other.y;

        return *this;
    }

};

// Not member of Vector2f
inline Vector2f operator+(Vector2f a, const Vector2f& b)
{
  a += b;
  return a;
}

double dot(const Vector2f& a, const Vector2f& b)
{
    return a.getX()*b.getX() + a.getY()*b.getY();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top