Cos() public static method

public static Cos ( float f ) : float
f float
return float
Exemplo n.º 1
0
        /// <summary>
        /// 更新相机位置
        /// </summary>
        private void UpdatePosition()
        {
            Vector3 targetPos = this.tank.Point;

            Vector3 cameraPos;

            float d = this.distance * Mathf.Cos(roll);

            float height = this.distance * Mathf.Sin(roll);

            cameraPos.x = targetPos.x + d * Mathf.Sin(rot);

            cameraPos.y = targetPos.y + height;

            cameraPos.z = targetPos.z + d * Mathf.Cos(rot);

            this.MainCamera.transform.position = cameraPos;

            this.MainCamera.transform.LookAt(this.tank.Point);


            return;

            //Vector3 cameraPos = this.mainCamera.transform.position;
            this.mainCamera.transform.position = new Vector3(this.tank.Position.x, this.tank.Position.y + 5, this.tank.Position.z - 6);
            this.mainCamera.transform.LookAt(this.tank.Position);

            //this.mainCamera.transform.eulerAngles = new Vector3(30,0,0);
        }
Exemplo n.º 2
0
    private void GenerateBaseValues()
    {
        if (fromDegrees)
        {
            radians = (degrees * M.PI) / 180;
        }
        else
        {
            degrees = (radians * 180) / M.PI;
        }

        //If allowed, use time as input.
        t = (float)EditorApplication.timeSinceStartup;
        if (useTime)
        {
            radians = t;
            degrees = degrees = (radians * 180) / M.PI;
        }

        //Clamp the values to a readable range
        radians = M.Repeat(radians, 2 * M.PI);
        degrees = M.Repeat(degrees, 360);

        //local variables for simplicity
        sine    = M.Sin(radians);
        cosine  = M.Cos(radians);
        tangent = M.Tan(radians);
    }
Exemplo n.º 3
0
/**
 * Tweet cart is the whole script, fit in one tweet, i.e. code length must be <= 280 characters
 *
 * Tigra tweet cart shortcuts:
 *
 * Functions:
 * TIC() is called 60 times per second.
 *
 * Variables:
 * t:  elapsed time in seconds
 * f:  frame counter
 *
 * Aliases:
 * B:  bool
 * F:  float
 * I:  int
 * M:  UnityEngine.Mathf
 * R:  UnityEngine.Random
 * S:  System.String
 * V2: UnityEngine.Vector2
 * V3: UnityEngine.Vector3
 * Z:  Tic80
 *
 * Delegates:
 * CD: circ & circb delegate
 * RD: rect & rectb delegate
 * TD: tri & trib delegate
 *
 * Beautify/minify C# online tool:
 * https://codebeautify.org/csharpviewer
 */
class Tc6 : Z { F v = 0, hz = 1, step, d = 1.05f; void TIC()
                {
                    cls(); if (btn(0))
                    {
                        hz *= d;
                    }
                    if (btn(1))
                    {
                        hz /= d;
                    }
                    v %= 240 / hz; v += 4; if (hz < 1)
                    {
                        step = 1;
                    }
                    else if (hz > 50)
                    {
                        step = .02f;
                    }
                    else
                    {
                        step = 1 / hz;
                    } for (F x = -v; x < 240; x += step)
                    {
                        F y = 68 + 40 * M.Cos(x * M.PI / 120 * hz); pix(x + v, y, 3);
                    }
                    print(M.Log(hz) / M.Log(d), 1, 127); line(0, 67, 240, 67, 3);
                }
Exemplo n.º 4
0
        /// <summary>
        /// Rotates the given Vector2 counterclockwise by the given angle
        /// </summary>
        public static U.Vector2 RotateVector2(U.Vector2 vec, float angle)
        {
            angle = U.Mathf.Deg2Rad * angle;
            var _sinAngle = Mathf.Sin(angle);
            var _cosAngle = Mathf.Cos(angle);

            return(new U.Vector2(_cosAngle * vec.x - _sinAngle * vec.y, _sinAngle * vec.x + _cosAngle * vec.y));
        }
Exemplo n.º 5
0
    private void DrawPendulum()
    {
        //Draw Pendulum
        float deg         = sine * maxDeg;
        float rad         = M.Deg2Rad * deg;
        V3    pundulumPos = new V3(M.Sin(rad * timeScale), -M.Cos(rad * timeScale), 0);

        G.DrawWireSphere(pundulumPos + V3.left * 3, .2f);
        G.DrawLine(V3.zero + V3.left * 3, pundulumPos + V3.left * 3);
    }
Exemplo n.º 6
0
    private void DrawGraph()
    {
        //Draw Graph of the curves
        G.color = C.white;
        V3 offset = V3.down * 2 + V3.right * -1;

        G.DrawRay(offset + V3.up * .5f, V3.down * 1);
        G.DrawRay(offset + V3.down * .5f, V3.right * 2);

        G.color = C.gray;
        G.DrawRay(offset + V3.up * .5f, V3.right * 2);
        G.DrawRay(offset, V3.right * 2);

        G.DrawRay(offset + V3.up * .5f + V3.right * M.Repeat(radians / M.PI, 2), V3.down * 1);

        //Draw Sine
        G.color = C.red;
        offset  = V3.down * 2 + V3.right * -1;
        V3 last = new V3(0, 0, 0) + offset;

        for (int i = 1; i <= 360; i++)
        {
            V3 point = new V3((float)i / 180, M.Sin(M.Deg2Rad * i) * .5f, 0) + offset;

            G.DrawLine(last, point);
            last = point;
        }
        //Draw Cosine
        G.color = C.blue;
        offset  = V3.down * 2 + V3.right * -1;
        last    = new V3(0, .5f, 0) + offset;
        for (int i = 1; i <= 360; i++)
        {
            V3 point = new V3((float)i / 180, M.Cos(M.Deg2Rad * i) * .5f, 0) + offset;

            G.DrawLine(last, point);
            last = point;
        }
        //Draw Tangent
        if (showTan)
        {
            G.color = C.yellow;
            offset  = V3.down * 2 + V3.right * -1;
            last    = new V3(0, .5f, 0) + offset;
            for (int i = 1; i <= 360; i++)
            {
                V3 point = new V3((float)i / 180, M.Tan(M.Deg2Rad * i) * .5f, 0) + offset;

                G.DrawLine(last, point);
                last = point;
            }
        }
    }
Exemplo n.º 7
0
    /// <summary>
    /// Sinusoidal easing in (smooth start) between two points (a, b).
    /// </summary>
    /// <param name="a">Start point for the easing (0 by default).</param>
    /// <param name="b">End point for the easing (1 by default).</param>
    /// <param name="t">Percentage of the easing completed from 0 to 1.</param>
    public static float Sin_EaseIn(float a, float b, float t)
    {
        if (t > 1.0F)
        {
            t = 1.0F;
        }
        if (t < 0.0F)
        {
            t = 0.0F;
        }

        float x = (float)-Math.Cos(t * pi / 2.0F) + 1.0F; // F(x) =  -cos(x*pi/2)+1 for x in (0,1)

        return(a + x * (b - a));
    }
Exemplo n.º 8
0
    public static float Sin_EaseInOut(float a, float b, float t)
    {
        if (t > 1.0F)
        {
            t = 1.0F;
        }
        if (t < 0.0F)
        {
            t = 0.0F;
        }

        float x = (float)(Math.Cos(pi * (t + 1F)) + 1F) / 2F; // F(x) = (cos(pi*(x + 1)) + 1) / 2 for x in(0,1)

        return(a + x * (b - a));
    }
Exemplo n.º 9
0
        static void DrawVO(Vector2 circleCenter, float radius, Vector2 origin)
        {
            float alpha = Mathf.Atan2((origin - circleCenter).y, (origin - circleCenter).x);
            float gamma = radius / (origin - circleCenter).magnitude;
            float delta = gamma <= 1.0f ? Mathf.Abs(Mathf.Acos(gamma)) : 0;

            Draw.Debug.CircleXZ(FromXZ(circleCenter), radius, Color.black, alpha - delta, alpha + delta);
            Vector2 p1 = new Vector2(Mathf.Cos(alpha - delta), Mathf.Sin(alpha - delta)) * radius;
            Vector2 p2 = new Vector2(Mathf.Cos(alpha + delta), Mathf.Sin(alpha + delta)) * radius;

            Vector2 p1t = -new Vector2(-p1.y, p1.x);
            Vector2 p2t = new Vector2(-p2.y, p2.x);

            p1 += circleCenter;
            p2 += circleCenter;

            Debug.DrawRay(FromXZ(p1), FromXZ(p1t).normalized *100, Color.black);
            Debug.DrawRay(FromXZ(p2), FromXZ(p2t).normalized *100, Color.black);
        }
Exemplo n.º 10
0
/**
 * Tweet cart is the whole script, fit in one tweet, i.e. code length must be <= 280 characters
 *
 * Tigra tweet cart shortcuts:
 *
 * Functions:
 * TIC() is called 60 times per second.
 *
 * Variables:
 * t:  elapsed time in seconds
 * f:  frame counter
 *
 * Aliases:
 * B:  bool
 * F:  float
 * I:  int
 * M:  UnityEngine.Mathf
 * R:  UnityEngine.Random
 * S:  System.String
 * V2: UnityEngine.Vector2
 * V3: UnityEngine.Vector3
 * Z:  Tic80
 *
 * Delegates:
 * CD: circ & circb delegate
 * RD: rect & rectb delegate
 * TD: tri & trib delegate
 *
 * Beautify/minify C# online tool:
 * https://codebeautify.org/csharpviewer
 */
class Tc4 : Z { F PI2 = (F)2.0 * M.PI; I dx = 32, dy = 32, ts = 0; void TIC()
                {
                    cls(); if (dy < 0)
                    {
                        dy = 0;
                    }
                    if (dx < 0)
                    {
                        dx = 0;
                    }
                    for (F x = -dx; x < 220 + 2 * dx; x += dx)
                    {
                        for (F y = -dy; y < 136 + 2 * dy; y += dy)
                        {
                            for (F a = 0; a < PI2; a += PI2 / 8)
                            {
                                circ(x + 35 * M.Sin(a + t), y + 35 * M.Cos(a + t), 5, 15);
                            }
                        }
                    }
                }
Exemplo n.º 11
0
/**
 * Tweet cart is the whole script, fit in one tweet, i.e. code length must be <= 280 characters
 *
 * Tigra tweet cart shortcuts:
 *
 * Functions:
 * TIC() is called 60 times per second.
 *
 * Variables:
 * t:  elapsed time in seconds
 * f:  frame counter
 *
 * Aliases:
 * B:  bool
 * F:  float
 * I:  int
 * M:  UnityEngine.Mathf
 * R:  UnityEngine.Random
 * S:  System.String
 * V2: UnityEngine.Vector2
 * V3: UnityEngine.Vector3
 * Z:  Tic80
 *
 * Delegates:
 * CD: circ & circb delegate
 * RD: rect & rectb delegate
 * TD: tri & trib delegate
 *
 * Beautify/minify C# online tool:
 * https://codebeautify.org/csharpviewer
 */

class Tc1 : Z { F a, b; I[] d = { 2, 3, 4, 4 }; V2[] c = new V2[4]; void TIC()
                {
                    if (a == 0)
                    {
                        c[3] = new V2(96, 24);
                    }
                    if (a++ % 10 == 0)
                    {
                        cls(); b += R.Range(-1, 1) * M.PI / 4; int i; for (i = 0; i < 3; i++)
                        {
                            c[i] = c[i + 1];
                        }
                        c[3].x += M.Sin(b) * 4; c[3].y += M.Cos(b) * 4; CD f = circb; for (i = 0; i < 4; i++)
                        {
                            if (i == 3)
                            {
                                f = circ;
                            }
                            f(c[i].x, c[i].y, d[i], 6);
                        }
                    }
                }
Exemplo n.º 12
0
        /// <summary>
        /// Convert given degree rotation in given axis to orthogonal matrix rotation.
        /// </summary>
        /// <remarks>This method is much optimized than Euler(new Euler4(axis, degree))</remarks>
        public static Matrix4 Euler(int axis, float degree)
        {
            float s = Math.Sin(degree * Math.Deg2Rad), c = Math.Cos(degree * Math.Deg2Rad);
            var   m = identity;

            switch (axis)
            {
            case 0: m.ey.y = c; m.ez.z = c; m.ey.z = -s; m.ez.y = s; return(m);

            case 1: m.ex.x = c; m.ez.z = c; m.ex.z = s; m.ez.x = -s; return(m);

            case 2: m.ex.x = c; m.ey.y = c; m.ex.y = -s; m.ey.x = s; return(m);

            case 3: m.ex.x = c; m.ew.w = c; m.ex.w = -s; m.ew.x = s; return(m);

            case 4: m.ey.y = c; m.ew.w = c; m.ey.w = -s; m.ew.y = s; return(m);

            case 5: m.ez.z = c; m.ew.w = c; m.ez.w = -s; m.ew.z = s; return(m);

            default: throw new ArgumentOutOfRangeException("axis");
            }
        }
Exemplo n.º 13
0
        public void CircleXZ(Vector3 center, float radius, Color color, float startAngle = 0f, float endAngle = 2 *Mathf.PI)
        {
            int steps = 40;

#if UNITY_EDITOR
            if (gizmos)
            {
                steps = (int)Mathf.Clamp(Mathf.Sqrt(radius / UnityEditor.HandleUtility.GetHandleSize((UnityEngine.Gizmos.matrix * matrix).MultiplyPoint3x4(center))) * 25, 4, 40);
            }
#endif
            while (startAngle > endAngle)
            {
                startAngle -= 2 * Mathf.PI;
            }

            Vector3 prev = new Vector3(Mathf.Cos(startAngle) * radius, 0, Mathf.Sin(startAngle) * radius);
            for (int i = 0; i <= steps; i++)
            {
                Vector3 c = new Vector3(Mathf.Cos(Mathf.Lerp(startAngle, endAngle, i / (float)steps)) * radius, 0, Mathf.Sin(Mathf.Lerp(startAngle, endAngle, i / (float)steps)) * radius);
                Line(center + prev, center + c, color);
                prev = c;
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// 更新相机位置
        /// </summary>
        private void UpdatePosition()
        {
            Vector3 targetPos = this.tank.Point;

            Vector3 cameraPos;

            float d = this.distance * Mathf.Cos(roll);

            float height = this.distance * Mathf.Sin(roll);

            cameraPos.x = targetPos.x + d * Mathf.Sin(rot);

            cameraPos.y = targetPos.y + height;

            cameraPos.z = targetPos.z + d * Mathf.Cos(rot);

            this.MainCamera.transform.position = cameraPos;

            this.MainCamera.transform.LookAt(this.tank.Point);


            return;
        }
Exemplo n.º 15
0
 /** Returns the XZ coordinate of the involute of circle.
  * \see http://en.wikipedia.org/wiki/Involute
  */
 private static Vector3 InvoluteOfCircle(float a, float t)
 {
     return(new Vector3(a * (Mathf.Cos(t) + t * Mathf.Sin(t)), 0, a * (Mathf.Sin(t) - t * Mathf.Cos(t))));
 }
Exemplo n.º 16
0
        /// <summary>
        /// Convert degree euler to orthogonal matrix rotation individually.
        /// </summary>
        /// <remarks>
        /// This creates a rotation matrix that rotates a point by Y, Z, X, T, U, then V. In that order.
        /// </remarks>
        public static Matrix4 Euler(float x, float y, float z, float t, float u, float v)
        {
            // Multiplication matrices, in order
            float y2 = y * Math.Deg2Rad, a = Math.Cos(y2), b = Math.Sin(y2); // CW
            float z2 = z * Math.Deg2Rad, c = Math.Cos(z2), d = Math.Sin(z2); // CCW
            float x2 = x * Math.Deg2Rad, f = Math.Cos(x2), g = Math.Sin(x2); // CCW
            float t2 = t * Math.Deg2Rad, h = Math.Cos(t2), j = Math.Sin(t2); // CCW
            float u2 = u * Math.Deg2Rad, k = Math.Cos(u2), l = Math.Sin(u2); // CCW
            float v2 = v * Math.Deg2Rad, m = Math.Cos(v2), n = Math.Sin(v2); // CCW

            // Premultiplied code
            //var p1 = (b * g + a * d * f);
            //var p2 = (b * d * f + a * g);
            //var p3 = (c * j * k);
            //var p4 = -(d * j * k) + (c * f * l);
            //var p6 = (a * d * g - b * f);
            //var p7 = (a * f - b * d * g);
            //var p8 = (j * l);
            //var p9 = (c * h);
            //var p10 = (c * g);

            // This is corrected version than below (duh)
            return(new Matrix4(a * c * h,
                               -d * h,
                               b * c * h,
                               -j,
                               k * (a * d * f + b * g) - a * c * j * l,
                               c * f * k + d * j * l,
                               k * (b * d * f - a * g) - b * c * j * l,
                               -h * l,
                               -l * n * (a * d * f + b * g) + m * (a * d * g - b * f) - a * c * j * k * n,
                               c * g * m + d * j * k * n - c * f * l * n,
                               -l * n * (b * d * f - a * g) + m * (b * d * g + a * f) - b * c * j * k * n,
                               -h * k * n,
                               l * m * (a * d * f + b * g) + n * (a * d * g - b * f) + a * c * j * k * m,
                               c * f * l * m - d * j * k * m + c * g * n,
                               l * m * (b * d * f - a * g) + n * (b * d * g + a * f) + b * c * j * k * m,
                               h * k * m
                               ));

            // matrix{{ach, dh, -bch, -j}, {k(bg-adf)-acjl, cfk-djl, k(bdf+ag)+bcjl, -hl},
            // { -ln(bg-adf)+m(adg+bf)-acjkn, -cgm-cfln-djkn, -ln(bdf+ag)+m(af-bdg)+bcjkn, -hkn},
            // { lm(bg-adf)+n(adg+bf)+acjkm, cflm+djkm-cgn, lm(bdf+ag)+n(af-bdg)-bcjkm, hkm}}

            // matrix{{ach, -dh, bch, -j}, {k(adf+bg)-acjl, cfk+djl, k(bdf-ag)-bcjl, -hl},
            // { -ln(adf+bg)+m(adg-bf)-acjkn, cgm+djkn-cfln, -ln(bdf-ag)+m(bdg+af)-bcjkn, -hkn},
            // { lm(adf+bg)+n(adg-bf)+acjkm, cflm-djkm+cgn, lm(bdf-ag)+n(bdg+af)+bcjkm, hkm}}

            //return new Matrix4(
            //     a * p9,
            //     -d * h,
            //     b * p9,
            //     -j,
            //     k * p1 - a * c * p8,
            //     c * f * k + d * p8,
            //     k * p2 - b * c * p8,
            //     -h * l,
            //     m * p6 - (a * p3 + l * p1) * n,
            //     p10 * m - p4 * n,
            //     m * p7 + (b * p3 - l * p2) * n,
            //     -h * k * n,
            //     n * p6 + (a * p3 + l * p1) * m,
            //     -p10 * n + p4 * m,
            //      n * p7 - (b * p3 - l * p2) * m,
            //     h * k * m
            //  );
        }
Exemplo n.º 17
0
        RasterizationMesh RasterizeCapsuleCollider(float radius, float height, Bounds bounds, Matrix4x4 localToWorldMatrix)
        {
            // Calculate the number of rows to use
            // grows as sqrt(x) to the radius of the sphere/capsule which I have found works quite well
            int rows = Mathf.Max(4, Mathf.RoundToInt(colliderRasterizeDetail * Mathf.Sqrt(localToWorldMatrix.MultiplyVector(Vector3.one).magnitude)));

            if (rows > 100)
            {
                Debug.LogWarning("Very large detail for some collider meshes. Consider decreasing Collider Rasterize Detail (RecastGraph)");
            }

            int cols = rows;

            Vector3[] verts;
            int[]     trisArr;

            // Check if we have already calculated a similar capsule
            CapsuleCache cached = null;

            for (int i = 0; i < capsuleCache.Count; i++)
            {
                CapsuleCache c = capsuleCache[i];
                if (c.rows == rows && Mathf.Approximately(c.height, height))
                {
                    cached = c;
                }
            }

            if (cached == null)
            {
                // Generate a sphere/capsule mesh

                verts = new Vector3[(rows) * cols + 2];

                var tris = new List <int>();
                verts[verts.Length - 1] = Vector3.up;

                for (int r = 0; r < rows; r++)
                {
                    for (int c = 0; c < cols; c++)
                    {
                        verts[c + r * cols] = new Vector3(Mathf.Cos(c * Mathf.PI * 2 / cols) * Mathf.Sin((r * Mathf.PI / (rows - 1))), Mathf.Cos((r * Mathf.PI / (rows - 1))) + (r < rows / 2 ? height : -height), Mathf.Sin(c * Mathf.PI * 2 / cols) * Mathf.Sin((r * Mathf.PI / (rows - 1))));
                    }
                }

                verts[verts.Length - 2] = Vector3.down;

                for (int i = 0, j = cols - 1; i < cols; j = i++)
                {
                    tris.Add(verts.Length - 1);
                    tris.Add(0 * cols + j);
                    tris.Add(0 * cols + i);
                }

                for (int r = 1; r < rows; r++)
                {
                    for (int i = 0, j = cols - 1; i < cols; j = i++)
                    {
                        tris.Add(r * cols + i);
                        tris.Add(r * cols + j);
                        tris.Add((r - 1) * cols + i);

                        tris.Add((r - 1) * cols + j);
                        tris.Add((r - 1) * cols + i);
                        tris.Add(r * cols + j);
                    }
                }

                for (int i = 0, j = cols - 1; i < cols; j = i++)
                {
                    tris.Add(verts.Length - 2);
                    tris.Add((rows - 1) * cols + j);
                    tris.Add((rows - 1) * cols + i);
                }

                // Add calculated mesh to the cache
                cached        = new CapsuleCache();
                cached.rows   = rows;
                cached.height = height;
                cached.verts  = verts;
                cached.tris   = tris.ToArray();
                capsuleCache.Add(cached);
            }

            // Read from cache
            verts   = cached.verts;
            trisArr = cached.tris;

            return(new RasterizationMesh(verts, trisArr, bounds, localToWorldMatrix));
        }
Exemplo n.º 18
0
        public void VoxelizeInput(GraphTransform graphTransform, Bounds graphSpaceBounds)
        {
            AstarProfiler.StartProfile("Build Navigation Mesh");

            AstarProfiler.StartProfile("Voxelizing - Step 1");

            // Transform from voxel space to graph space.
            // then scale from voxel space (one unit equals one voxel)
            // Finally add min
            PF.Matrix4x4 voxelMatrix = PF.Matrix4x4.TRS(graphSpaceBounds.min, PF.Quaternion.identity, Vector3.one) * PF.Matrix4x4.Scale(new PF.Vector3(cellSize, cellHeight, cellSize));
            transformVoxel2Graph = new GraphTransform(voxelMatrix);

            // Transform from voxel space to world space
            // add half a voxel to fix rounding
            transform = graphTransform * voxelMatrix * PF.Matrix4x4.TRS(new Vector3(0.5f, 0, 0.5f), PF.Quaternion.identity, Vector3.one);

            int maximumVoxelYCoord = (int)(graphSpaceBounds.size.y / cellHeight);

            AstarProfiler.EndProfile("Voxelizing - Step 1");

            AstarProfiler.StartProfile("Voxelizing - Step 2 - Init");

            // Cosine of the slope limit in voxel space (some tweaks are needed because the voxel space might be stretched out along the y axis)
            float slopeLimit = Mathf.Cos(Mathf.Atan(Mathf.Tan(maxSlope * Mathf.Deg2Rad) * (cellSize / cellHeight)));

            // Temporary arrays used for rasterization
            float[] vTris    = new float[3 * 3];
            float[] vOut     = new float[7 * 3];
            float[] vRow     = new float[7 * 3];
            float[] vCellOut = new float[7 * 3];
            float[] vCell    = new float[7 * 3];

            if (inputMeshes == null)
            {
                throw new System.NullReferenceException("inputMeshes not set");
            }

            // Find the largest lengths of vertex arrays and check for meshes which can be skipped
            int maxVerts = 0;

            for (int m = 0; m < inputMeshes.Count; m++)
            {
                maxVerts = System.Math.Max(inputMeshes[m].vertices.Length, maxVerts);
            }

            // Create buffer, here vertices will be stored multiplied with the local-to-voxel-space matrix
            var verts = new Vector3[maxVerts];

            AstarProfiler.EndProfile("Voxelizing - Step 2 - Init");

            AstarProfiler.StartProfile("Voxelizing - Step 2");

            // This loop is the hottest place in the whole rasterization process
            // it usually accounts for around 50% of the time
            for (int m = 0; m < inputMeshes.Count; m++)
            {
                RasterizationMesh mesh = inputMeshes[m];
                var meshMatrix         = mesh.matrix;

                // Flip the orientation of all faces if the mesh is scaled in such a way
                // that the face orientations would change
                // This happens for example if a mesh has a negative scale along an odd number of axes
                // e.g it happens for the scale (-1, 1, 1) but not for (-1, -1, 1) or (1,1,1)
                var flipOrientation = UnityHelper.ReversesFaceOrientations(meshMatrix);

                Vector3[] vs         = mesh.vertices;
                int[]     tris       = mesh.triangles;
                int       trisLength = mesh.numTriangles;

                // Transform vertices first to world space and then to voxel space
                for (int i = 0; i < vs.Length; i++)
                {
                    verts[i] = transform.InverseTransform(meshMatrix.MultiplyPoint3x4(vs[i]));
                }

                int mesharea = mesh.area;

                for (int i = 0; i < trisLength; i += 3)
                {
                    Vector3 p1 = verts[tris[i]];
                    Vector3 p2 = verts[tris[i + 1]];
                    Vector3 p3 = verts[tris[i + 2]];

                    if (flipOrientation)
                    {
                        var tmp = p1;
                        p1 = p3;
                        p3 = tmp;
                    }

                    int minX = (int)(Utility.Min(p1.x, p2.x, p3.x));
                    int minZ = (int)(Utility.Min(p1.z, p2.z, p3.z));

                    int maxX = (int)System.Math.Ceiling(Utility.Max(p1.x, p2.x, p3.x));
                    int maxZ = (int)System.Math.Ceiling(Utility.Max(p1.z, p2.z, p3.z));

                    minX = Mathf.Clamp(minX, 0, voxelArea.width - 1);
                    maxX = Mathf.Clamp(maxX, 0, voxelArea.width - 1);
                    minZ = Mathf.Clamp(minZ, 0, voxelArea.depth - 1);
                    maxZ = Mathf.Clamp(maxZ, 0, voxelArea.depth - 1);

                    // Check if the mesh is completely out of bounds
                    if (minX >= voxelArea.width || minZ >= voxelArea.depth || maxX <= 0 || maxZ <= 0)
                    {
                        continue;
                    }

                    Vector3 normal;

                    int area;

                    //AstarProfiler.StartProfile ("Rasterize...");

                    normal = Vector3.Cross(p2 - p1, p3 - p1);

                    float cosSlopeAngle = Vector3.Dot(normal.normalized, Vector3.up);

                    if (cosSlopeAngle < slopeLimit)
                    {
                        area = UnwalkableArea;
                    }
                    else
                    {
                        area = 1 + mesharea;
                    }

                    Utility.CopyVector(vTris, 0, p1);
                    Utility.CopyVector(vTris, 3, p2);
                    Utility.CopyVector(vTris, 6, p3);

                    for (int x = minX; x <= maxX; x++)
                    {
                        int nrow = clipper.ClipPolygon(vTris, 3, vOut, 1F, -x + 0.5F, 0);

                        if (nrow < 3)
                        {
                            continue;
                        }

                        nrow = clipper.ClipPolygon(vOut, nrow, vRow, -1F, x + 0.5F, 0);

                        if (nrow < 3)
                        {
                            continue;
                        }

                        float clampZ1 = vRow[2];
                        float clampZ2 = vRow[2];
                        for (int q = 1; q < nrow; q++)
                        {
                            float val = vRow[q * 3 + 2];
                            clampZ1 = System.Math.Min(clampZ1, val);
                            clampZ2 = System.Math.Max(clampZ2, val);
                        }

                        int clampZ1I = Mathf.Clamp((int)System.Math.Round(clampZ1), 0, voxelArea.depth - 1);
                        int clampZ2I = Mathf.Clamp((int)System.Math.Round(clampZ2), 0, voxelArea.depth - 1);


                        for (int z = clampZ1I; z <= clampZ2I; z++)
                        {
                            //AstarProfiler.StartFastProfile(1);
                            int ncell = clipper.ClipPolygon(vRow, nrow, vCellOut, 1F, -z + 0.5F, 2);

                            if (ncell < 3)
                            {
                                //AstarProfiler.EndFastProfile(1);
                                continue;
                            }

                            ncell = clipper.ClipPolygonY(vCellOut, ncell, vCell, -1F, z + 0.5F, 2);

                            if (ncell < 3)
                            {
                                //AstarProfiler.EndFastProfile(1);
                                continue;
                            }

                            //AstarProfiler.EndFastProfile(1);
                            //AstarProfiler.StartFastProfile(2);
                            float sMin = vCell[1];
                            float sMax = vCell[1];
                            for (int q = 1; q < ncell; q++)
                            {
                                float val = vCell[q * 3 + 1];
                                sMin = System.Math.Min(sMin, val);
                                sMax = System.Math.Max(sMax, val);
                            }

                            //AstarProfiler.EndFastProfile(2);
                            int maxi = (int)System.Math.Ceiling(sMax);

                            // Skip span if below or above the bounding box
                            if (maxi >= 0 && sMin <= maximumVoxelYCoord)
                            {
                                // Make sure mini >= 0
                                int mini = System.Math.Max(0, (int)sMin);

                                // Make sure the span is at least 1 voxel high
                                maxi = System.Math.Max(mini + 1, maxi);

                                voxelArea.AddLinkedSpan(z * voxelArea.width + x, (uint)mini, (uint)maxi, area, voxelWalkableClimb);
                            }
                        }
                    }
                }
                //AstarProfiler.EndFastProfile(0);
                //AstarProfiler.EndProfile ("Rasterize...");
            }
            AstarProfiler.EndProfile("Voxelizing - Step 2");
        }
Exemplo n.º 19
0
            /** Creates a VO for avoiding another agent.
             * \param center The position of the other agent relative to this agent.
             * \param offset Offset of the velocity obstacle. For example to account for the agents' relative velocities.
             * \param radius Combined radius of the two agents (radius1 + radius2).
             * \param inverseDt 1 divided by the local avoidance time horizon (e.g avoid agents that we will hit within the next 2 seconds).
             * \param inverseDeltaTime 1 divided by the time step length.
             */
            public VO(Vector2 center, Vector2 offset, float radius, float inverseDt, float inverseDeltaTime)
            {
                // Adjusted so that a parameter weightFactor of 1 will be the default ("natural") weight factor
                this.weightFactor = 1;
                weightBonus       = 0;

                //this.radius = radius;
                Vector2 globalCenter;

                circleCenter = center * inverseDt + offset;

                this.weightFactor = 4 * Mathf.Exp(-Sqr(center.sqrMagnitude / (radius * radius))) + 1;
                // Collision?
                if (center.magnitude < radius)
                {
                    colliding = true;

                    // 0.001 is there to make sure lin1.magnitude is not so small that the normalization
                    // below will return Vector2.zero as that will make the VO invalid and it will be ignored.
                    line1  = center.normalized * (center.magnitude - radius - 0.001f) * 0.3f * inverseDeltaTime;
                    dir1   = new Vector2(line1.y, -line1.x).normalized;
                    line1 += offset;

                    cutoffDir   = Vector2.zero;
                    cutoffLine  = Vector2.zero;
                    dir2        = Vector2.zero;
                    line2       = Vector2.zero;
                    this.radius = 0;
                }
                else
                {
                    colliding = false;

                    center      *= inverseDt;
                    radius      *= inverseDt;
                    globalCenter = center + offset;

                    // 0.001 is there to make sure cutoffDistance is not so small that the normalization
                    // below will return Vector2.zero as that will make the VO invalid and it will be ignored.
                    var cutoffDistance = center.magnitude - radius + 0.001f;

                    cutoffLine  = center.normalized * cutoffDistance;
                    cutoffDir   = new Vector2(-cutoffLine.y, cutoffLine.x).normalized;
                    cutoffLine += offset;

                    float alpha = Mathf.Atan2(-center.y, -center.x);

                    float delta = Mathf.Abs(Mathf.Acos(radius / center.magnitude));

                    this.radius = radius;

                    // Bounding Lines

                    // Point on circle
                    line1 = new Vector2(Mathf.Cos(alpha + delta), Mathf.Sin(alpha + delta));
                    // Vector tangent to circle which is the correct line tangent
                    // Note that this vector is normalized
                    dir1 = new Vector2(line1.y, -line1.x);

                    // Point on circle
                    line2 = new Vector2(Mathf.Cos(alpha - delta), Mathf.Sin(alpha - delta));
                    // Vector tangent to circle which is the correct line tangent
                    // Note that this vector is normalized
                    dir2 = new Vector2(line2.y, -line2.x);

                    line1 = line1 * radius + globalCenter;
                    line2 = line2 * radius + globalCenter;
                }

                segmentStart = Vector2.zero;
                segmentEnd   = Vector2.zero;
                segment      = false;
            }
Exemplo n.º 20
0
 public static float InOut(float k)
 {
     return(0.5f * (1f - Mathf.Cos(Mathf.PI * k)));
 }
Exemplo n.º 21
0
        public override void OnGUI()
        {
            base.OnGUI();
            if (selectedObject == null)
            {
                return;
            }

            Texture currentTexture;
            float   markerX, markerY, markerRot;

            Vector3 screenPos = Player.main.viewModelCamera.WorldToScreenPoint(selectedObject.transform.position);

            //if object is on screen
            if (screenPos.z > 0 &&
                screenPos.x >= 0 && screenPos.x < Screen.width &&
                screenPos.y >= 0 && screenPos.y < Screen.height)
            {
                currentTexture = circleTexture;
                markerX        = screenPos.x;
                //subtract from height to go from bottom up to top down
                markerY   = Screen.height - screenPos.y;
                markerRot = 0;
            }
            //if object is not on screen
            else
            {
                currentTexture = arrowTexture;
                //if the object is behind us, flip across the center
                if (screenPos.z < 0)
                {
                    screenPos.x = Screen.width - screenPos.x;
                    screenPos.y = Screen.height - screenPos.y;
                }

                //calculate new position of arrow (somewhere on the edge)
                Vector3 screenCenter = new Vector3(Screen.width, Screen.height, 0) / 2f;
                Vector3 originPos    = screenPos - screenCenter;

                float angle = Mathf.Atan2(originPos.y, originPos.x) - (90 * Mathf.Deg2Rad);
                float cos   = Mathf.Cos(angle);
                float sin   = Mathf.Sin(angle);
                float m     = cos / -sin;

                Vector3 screenBounds = screenCenter * 0.9f;

                if (cos > 0)
                {
                    screenPos = new Vector3(screenBounds.y / m, screenBounds.y, 0);
                }
                else
                {
                    screenPos = new Vector3(-screenBounds.y / m, -screenBounds.y, 0);
                }
                if (screenPos.x > screenBounds.x)
                {
                    screenPos = new Vector3(screenBounds.x, screenBounds.x * m, 0);
                }
                else if (screenPos.x < -screenBounds.x)
                {
                    screenPos = new Vector3(-screenBounds.x, -screenBounds.x * m, 0);
                }

                screenPos += screenCenter;

                markerX   = screenPos.x;
                markerY   = Screen.height - screenPos.y;
                markerRot = -angle * Mathf.Rad2Deg;
            }

            float markerSizeX = currentTexture.width;
            float markerSizeY = currentTexture.height;

            GUI.matrix = Matrix4x4.Translate(new Vector3(markerX, markerY, 0)) *
                         Matrix4x4.Rotate(Quaternion.Euler(0, 0, markerRot)) *
                         Matrix4x4.Scale(new Vector3(0.5f, 0.5f, 0.5f)) *
                         Matrix4x4.Translate(new Vector3(-markerSizeX / 2, -markerSizeY / 2, 0));

            GUI.DrawTexture(new Rect(0, 0, markerSizeX, markerSizeY), currentTexture);
            GUI.matrix = Matrix4x4.identity;
        }
Exemplo n.º 22
0
 /// <summary>
 /// Modeled after half sine wave
 /// </summary>
 static public float SineEaseInOut(float p)
 {
     return(0.5f * (1 - Math.Cos(p * PI)));
 }
Exemplo n.º 23
0
 public static float In(float k)
 {
     return(1f - Mathf.Cos(k * Mathf.PI / 2f));
 }