墙壁的球反射有一个角度不运作

时间:2014-07-13 14:47:22

标签: java math collision dot-product

我正试图让一个球反弹墙。墙壁可以处于任何角度,并且球可以以任何角度撞击墙壁。球具有速度矢量。我已经计算并标准化了球碰撞的墙的法线。下面的代码是我用来计算点积的代码:

public float dotProduct(Vector2 v1, Vector2 v2){
    float theta1 = (float) (Math.atan(v1.getY()/v1.getX()));
    float theta2 = (float) (Math.atan(v2.getY()/v2.getX()));
    float alpha = theta1 - theta2;
    float v1Magnitude = (float) Math.sqrt(Math.pow(Math.abs(v1.getX()), 2) + Math.pow(Math.abs(v1.getY()), 2));
    float v2Magnitude = (float) Math.sqrt(Math.pow(Math.abs(v2.getX()), 2) + Math.pow(Math.abs(v2.getY()), 2));
    return (float) Math.abs((v1Magnitude * v2Magnitude * Math.cos(alpha)));
}

出于某种原因,球会以一种奇怪的方向高速反弹。这是计算反射速度的主要函数:

startX,startY,stopX和stopY是墙的坐标。

   public Vector2 calculateReflection(float startX, float startY, float stopX, float stopY){
    Vector2 normal;

    normal = new Vector2(-(stopY - startY), (stopX - startX));

    normal = normalize(normal);

    float velocityDotProduct = dotProduct(velocity, normal);
    Vector2 reflectionVelocity = new Vector2(velocity.getX() - 2*velocityDotProduct*normal.getX(), 
                                             velocity.getY() - 2*velocityDotProduct*normal.getY());

    return reflectionVelocity;
}

有谁知道我做错了什么?

1 个答案:

答案 0 :(得分:0)

从A(ax,ay)到E(ex,ey)的墙的法向量应为

-(ey - ay), ex - ax

public Vector calculateReflection( Vector velocity){
    double velocityDotProduct = Vector.dotProduct(normal, velocity);
    Vector reflectionVelocity = 
       new Vector(velocity.getX() + 2*velocityDotProduct*normal.getX(),
       velocity.getY() + 2*velocityDotProduct*normal.getY());
    return reflectionVelocity;
}
public void normalize(){
    double d = Math.sqrt( x*x + y*y );
    x /= d;
    y /= d;
}

public static double dotProduct(Vector v1, Vector v2){
    double res = v1.getX()*v2.getX() + v1.getY()*v2.getY();
}

public class Reflect {
private Vector normal;

public Reflect(double begX, double begY, double endX, double endY ){
    normal = new Vector(-(endY - begY), endX - begX);
    normal.normalize();
    System.out.println( "normal: " + normal );
}

public Vector calculateReflection( Vector velocity){
     double velocityDotProduct = Vector.dotProduct(normal, velocity);
     Vector reflectionVelocity = 
       new Vector(velocity.getX() - 2*velocityDotProduct*normal.getX(),
           velocity.getY() - 2*velocityDotProduct*normal.getY());
     return reflectionVelocity;
}