0

ボールを壁で跳ねさせようとしています。壁は任意の角度に設定でき、ボールは任意の角度で壁に当たることができます。ボールには速度ベクトルがあります。ボールが衝突する壁の法線を計算して正規化しました。以下のこのコードは、内積を計算するために使用するものです。

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;
}

誰かが私が間違っていることを知っていますか?

4

1 に答える 1

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;
}
于 2014-07-13T15:14:29.370 に答える