⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 vectorops.java

📁 一个J2Me的赛车游戏
💻 JAVA
字号:
/**
 * A simple class that simplifies some vector math.
 */
public class VectorOps
{
    /** Calculates the dot product of two vectors.
     * Takes for granted that the vectors v and u exist
     * in the 3-dimensional room.
     */
    public static float dotProduct(float[] v, float[] u)
    {
        return v[0] * u[0] + v[1] * u[1] + v[2] * u[2];
    }

    /** Calculates the cross product of two vectors.
     * Takes for granted that the vectors v and u exist
     * in the 3-dimensional room.
     */
    public static float[] crossProduct(float[] v, float[] u)
    {
        float[] newVec = {v[1] * u[2] - v[2] * u[1], v[2] * u[0] - v[0] * u[2], v[0] * u[1] - v[1] * u[0]};
        return newVec;
    }

    /** Calculates length of vector v */
    public static float length(float[] v)
    {
        return (float)Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
    }


    /** Projects vector v onto vector u */
    public static float[] project(float[] v, float[] u)
    {
        float lenU = length(u);
        float scalar = dotProduct(v, u) / (lenU * lenU);
        return scalarMul(scalar, u);
    }

    /** Calculates the normal of the plane defined by vector v and vector u */
    public static float[] calcNormal(float[] v, float[] u)
    {
        float[] cross = crossProduct(v, u);
        return normalize(cross);
    }

    /** Normalizes a vector (e.g. makes its length = 1) */
    public static float[] normalize(float[] v)
    {
        float len = length(v);
        float[] newVec = {v[0] / len, v[1] / len, v[2] / len};
        return newVec;
    }

    /** Multiplies a vector with a scalar */
    public static float[] scalarMul(float scalar, float[] v)
    {
        float[] newVec = {v[0] * scalar, v[1] * scalar, v[2] * scalar};
        return newVec;
    }

    /** Subtracts two vectors. v - u */
    public static float[] sub(float[] v, float[] u)
    {
        float[] newVec = {v[0] - u[0], v[1] - u[1], v[2] - u[2]};
        return newVec;
    }

    /** Adds two vectors. v - u */
    public static float[] add(float[] v, float[] u)
    {
        float[] newVec = {v[0] + u[0], v[1] + u[1], v[2] + u[2]};
        return newVec;
    }

    /** Mirrors the vector v in the plane that has the normal vector n */
    public static float[] mirror(float[] v, float[] n)
    {
        float[] u = VectorOps.project(v, n);
        return VectorOps.sub(v, VectorOps.scalarMul(2.0f, u));
    }

    /** Made for simple construction of a vector */
    public static float[] vector(float x, float y, float z)
    {
        float[] v = {x, y, z};
        return v;
    }

    /** Made for debugging. Transforms a vector to a String. */
    public static String toString(float[] v)
    {
        return "(" + v[0] + ", " + v[1] + ", " + v[2] + ")";
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -