Beispiel #1
0
        /// <summary>
        /// 通过起始点和速度反推俯仰角
        /// </summary>
        public static float ParabolaGetAngle(Vector3 start, Vector3 end, float v)
        {
            float tempRad = Mathf.Asin(9.8f * (start - end).magnitude / (v * v));

            return(tempRad * Mathf.Rad2Deg / 2);
        }
 public static float ConvertFrustrumLightCandelaToLumen(float intensity, float angleA, float angleB)
 {
     return(intensity * (4.0f * Mathf.Asin(Mathf.Sin(angleA / 2.0f) * Mathf.Sin(angleB / 2.0f))));
 }
Beispiel #3
0
        protected override void Impact(Thing hitThing)
        {
            Map map = base.Map;

            base.Impact(hitThing);
            ModOptions.SettingsRef settingsRef = new ModOptions.SettingsRef();
            Pawn pawn = this.launcher as Pawn;
            CompAbilityUserMagic comp = pawn.GetComp <CompAbilityUserMagic>();
            MagicPowerSkill      pwr  = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_Fireclaw.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_Fireclaw_pwr");
            MagicPowerSkill      ver  = pawn.GetComp <CompAbilityUserMagic>().MagicData.MagicPowerSkill_Fireclaw.FirstOrDefault((MagicPowerSkill x) => x.label == "TM_Fireclaw_ver");

            pwrVal = pwr.level;
            verVal = ver.level;
            if (pawn.story.traits.HasTrait(TorannMagicDefOf.Faceless))
            {
                MightPowerSkill mpwr = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_pwr");
                MightPowerSkill mver = pawn.GetComp <CompAbilityUserMight>().MightData.MightPowerSkill_Mimic.FirstOrDefault((MightPowerSkill x) => x.label == "TM_Mimic_ver");
                pwrVal = mpwr.level;
                verVal = mver.level;
            }
            if (settingsRef.AIHardMode && !pawn.IsColonist)
            {
                pwrVal = 3;
                verVal = 3;
            }
            IntVec3 target = base.Position;
            IntVec3 origin = this.origin.ToIntVec3();

            if (cflag)
            {
                hyp      = Mathf.Sqrt((Mathf.Pow(origin.x - target.x, 2)) + (Mathf.Pow(origin.z - target.z, 2)));
                duration = (Mathf.RoundToInt(hyp) + 7) * 2;
                angleRad = Mathf.Asin(Mathf.Abs(origin.x - target.x) / hyp);
                angleDeg = Mathf.Rad2Deg * angleRad;
                xProb    = angleDeg / 90;
                cflag    = false; //dont redo calculations
            }

            if (oflag)
            {
                //this.currentPos[j] = origin;
                //this.posAge[j] = 0;
                //this.posFlag[j] = true;
                //this.j++;
                currentPos = origin;
                posFlag    = true;
                pos11Age   = 0;
                oflag      = false;
            }


            if (this.primed == true)
            {
                if (((this.delay + this.lastStrike) < this.age))
                {
                    float rand  = (float)Rand.Range(0, 100);
                    bool  flag  = rand <= (xProb * 100);
                    int   rand2 = Rand.Range(0, 10);                    //used for variance

                    if (rand >= 40 && !pos1Flag && posFlag && this.age >= 10)
                    {
                        currentPos1 = currentPos;
                        pos1Flag    = true;
                        pos1Age     = this.age;
                    }
                    if (rand2 < 3 && !pos11Flag && pos1Flag && this.age >= 15 && verVal >= 1)
                    {
                        currentPos11 = currentPos1;
                        pos11Flag    = true;
                        pos11Age     = this.age;
                    }
                    if (rand2 < 3 && !pos12Flag && pos11Flag && this.age >= 25 && verVal >= 2)
                    {
                        currentPos12 = currentPos1;
                        pos12Flag    = true;
                        pos12Age     = this.age;
                    }
                    if (rand >= 40 && !pos2Flag && pos1Flag && this.age >= 20)
                    {
                        currentPos2 = currentPos;
                        pos2Flag    = true;
                        pos2Age     = this.age;
                    }
                    if (rand2 < 3 && !pos21Flag && pos2Flag && this.age >= 25 && verVal >= 1)
                    {
                        currentPos21 = currentPos2;
                        pos21Flag    = true;
                        pos21Age     = this.age;
                    }
                    if (rand2 < 3 && !pos22Flag && pos21Flag && this.age >= 35 && verVal >= 2)
                    {
                        currentPos22 = currentPos2;
                        pos22Flag    = true;
                        pos22Age     = this.age;
                    }
                    if (rand >= 40 && !pos3Flag && pos2Flag && this.age >= 30)
                    {
                        currentPos3 = currentPos;
                        pos3Flag    = true;
                        pos3Age     = this.age;
                    }
                    if (rand2 < 3 && !pos31Flag && pos3Flag && this.age >= 35 && verVal >= 1)
                    {
                        currentPos31 = currentPos3;
                        pos31Flag    = true;
                        pos31Age     = this.age;
                    }
                    if (rand >= 40 && !pos4Flag && pos3Flag && this.age >= 40)
                    {
                        currentPos4 = currentPos;
                        pos4Flag    = true;
                        pos4Age     = this.age;
                    }
                    if (rand >= 40 && !pos5Flag && pos4Flag && this.age >= 45)
                    {
                        currentPos5 = currentPos;
                        pos5Flag    = true;
                        pos5Age     = this.age;
                    }

                    //strike
                    if (posFlag && posFlagw)
                    {
                        currentPos = GetNewPos(currentPos, origin.x <= target.x, origin.z <= target.z, this.age >= (((duration + posAge) / 2)), 0, 0, xProb, 1 - xProb);
                        try
                        {
                            if ((currentPos.GetTerrain(base.Map).passability == Traversability.Impassable) || !currentPos.Walkable(base.Map))
                            {
                                this.posFlagw = false;
                            }
                            else
                            {
                                if (currentPos.x != origin.x & currentPos.z != origin.z)
                                {
                                    if (verVal >= 3)
                                    {
                                        this.FireExplosion(pwrVal, currentPos, map, 1.2f);
                                    }
                                    else
                                    {
                                        this.FireExplosion(pwrVal, currentPos, map, 0.4f);
                                    }
                                    this.lastStrike = this.age;
                                }
                            }
                        }
                        catch
                        {
                            this.posFlagw = false;
                        }
                    }
                    //1
                    if (pos1Flag && pos1Flagw)
                    {
                        currentPos1 = GetNewPos(currentPos1, origin.x <= target.x, origin.z <= target.z, this.age >= (((duration + pos1Age) / 2)), posx1weight, posz1weight, xProb, 1 - xProb);
                        try
                        {
                            if ((currentPos1.GetTerrain(base.Map).passability == Traversability.Impassable) || !currentPos1.Walkable(base.Map))
                            {
                                this.pos1Flagw = false;
                            }
                            else
                            {
                                if (currentPos1.x != origin.x & currentPos1.z != origin.z)
                                {
                                    if (verVal >= 3)
                                    {
                                        this.FireExplosion(pwrVal, currentPos1, map, 1.0f);
                                    }
                                    else
                                    {
                                        this.FireExplosion(pwrVal, currentPos1, map, 0.4f);
                                    }
                                }
                            }
                        }
                        catch
                        {
                            this.pos1Flagw = false;
                        }
                    }
                    if (pos11Flag && pos11Flagw)
                    {
                        currentPos11 = GetNewPos(currentPos11, origin.x <= target.x, origin.z <= target.z, this.age >= (((duration + pos11Age) / 2)), posx1weight * 1.5f, posz1weight * 1.5f, xProb, 1 - xProb);
                        try
                        {
                            if ((currentPos11.GetTerrain(base.Map).passability == Traversability.Impassable) || !currentPos11.Walkable(base.Map))
                            {
                                this.pos11Flagw = false;
                            }
                            else
                            {
                                if (currentPos11.x != origin.x & currentPos11.z != origin.z)
                                {
                                    if (verVal >= 3)
                                    {
                                        this.FireExplosion(pwrVal, currentPos11, map, 0.8f);
                                    }
                                    else
                                    {
                                        this.FireExplosion(pwrVal, currentPos11, map, 0.4f);
                                    }
                                }
                            }
                        }
                        catch
                        {
                            this.pos11Flagw = false;
                        }
                    }
                    if (pos12Flag && pos12Flagw)
                    {
                        currentPos12 = GetNewPos(currentPos12, origin.x <= target.x, origin.z <= target.z, this.age >= (((duration + pos12Age) / 2)), posx1weight * 2f, posz1weight * 2f, xProb, 1 - xProb);
                        try
                        {
                            if ((currentPos12.GetTerrain(base.Map).passability == Traversability.Impassable) || !currentPos12.Walkable(base.Map))
                            {
                                this.pos12Flagw = false;
                            }
                            else
                            {
                                if (currentPos12.x != origin.x & currentPos12.z != origin.z)
                                {
                                    if (verVal >= 3)
                                    {
                                        this.FireExplosion(pwrVal, currentPos12, map, 0.8f);
                                    }
                                    else
                                    {
                                        this.FireExplosion(pwrVal, currentPos12, map, 0.4f);
                                    }
                                }
                            }
                        }
                        catch
                        {
                            this.pos12Flagw = false;
                        }
                    }
                    //2
                    if (pos2Flag && pos2Flagw)
                    {
                        currentPos2 = GetNewPos(currentPos2, origin.x <= target.x, origin.z <= target.z, this.age >= (((duration + pos2Age) / 2)), posx2weight, posz2weight, xProb, 1 - xProb);
                        try
                        {
                            if ((currentPos2.GetTerrain(base.Map).passability == Traversability.Impassable) || !currentPos2.Walkable(base.Map))
                            {
                                this.pos2Flagw = false;
                            }
                            else
                            {
                                if (currentPos2.x != origin.x & currentPos2.z != origin.z)
                                {
                                    if (verVal >= 3)
                                    {
                                        this.FireExplosion(pwrVal, currentPos2, map, 1.0f);
                                    }
                                    else
                                    {
                                        this.FireExplosion(pwrVal, currentPos2, map, 0.4f);
                                    }
                                }
                            }
                        }
                        catch
                        {
                            this.pos2Flagw = false;
                        }
                    }
                    if (pos21Flag && pos21Flagw)
                    {
                        currentPos21 = GetNewPos(currentPos21, origin.x <= target.x, origin.z <= target.z, this.age >= (((duration + pos21Age) / 2)), posx2weight * 1.5f, posz2weight * 1.5f, xProb, 1 - xProb);
                        try
                        {
                            if ((currentPos21.GetTerrain(base.Map).passability == Traversability.Impassable) || !currentPos21.Walkable(base.Map))
                            {
                                this.pos21Flagw = false;
                            }
                            else
                            {
                                if (currentPos21.x != origin.x & currentPos21.z != origin.z)
                                {
                                    if (verVal >= 3)
                                    {
                                        this.FireExplosion(pwrVal, currentPos21, map, 0.8f);
                                    }
                                    else
                                    {
                                        this.FireExplosion(pwrVal, currentPos21, map, 0.4f);
                                    }
                                }
                            }
                        }
                        catch
                        {
                            this.pos21Flagw = false;
                        }
                    }
                    if (pos22Flag && pos22Flagw)
                    {
                        currentPos22 = GetNewPos(currentPos22, origin.x <= target.x, origin.z <= target.z, this.age >= (((duration + pos22Age) / 2)), posx2weight * 2f, posz2weight * 2f, xProb, 1 - xProb);
                        try
                        {
                            if ((currentPos22.GetTerrain(base.Map).passability == Traversability.Impassable) || !currentPos22.Walkable(base.Map))
                            {
                                this.pos22Flagw = false;
                            }
                            else
                            {
                                if (currentPos22.x != origin.x & currentPos22.z != origin.z)
                                {
                                    if (verVal >= 3)
                                    {
                                        this.FireExplosion(pwrVal, currentPos22, map, 0.8f);
                                    }
                                    else
                                    {
                                        this.FireExplosion(pwrVal, currentPos22, map, 0.4f);
                                    }
                                }
                            }
                        }
                        catch
                        {
                            this.pos22Flagw = false;
                        }
                    }
                    //3
                    if (pos3Flag && pos3Flagw)
                    {
                        currentPos3 = GetNewPos(currentPos3, origin.x <= target.x, origin.z <= target.z, this.age >= (((duration + pos3Age) / 2)), posx3weight, posz3weight, xProb, 1 - xProb);
                        try
                        {
                            if ((currentPos3.GetTerrain(base.Map).passability == Traversability.Impassable) || !currentPos3.Walkable(base.Map))
                            {
                                this.pos3Flagw = false;
                            }
                            else
                            {
                                if (verVal >= 3)
                                {
                                    this.FireExplosion(pwrVal, currentPos3, map, 1.0f);
                                }
                                else
                                {
                                    this.FireExplosion(pwrVal, currentPos3, map, 0.4f);
                                }
                            }
                        }
                        catch
                        {
                            this.pos3Flagw = false;
                        }
                    }
                    if (pos31Flag && pos31Flagw)
                    {
                        currentPos31 = GetNewPos(currentPos31, origin.x <= target.x, origin.z <= target.z, this.age >= (((duration + pos31Age) / 2)), posx3weight * 1.5f, posz3weight * 1.5f, xProb, 1 - xProb);
                        try
                        {
                            if ((currentPos31.GetTerrain(base.Map).passability == Traversability.Impassable) || !currentPos31.Walkable(base.Map))
                            {
                                this.pos31Flagw = false;
                            }
                            else
                            {
                                if (verVal >= 3)
                                {
                                    this.FireExplosion(pwrVal, currentPos31, map, 0.8f);
                                }
                                else
                                {
                                    this.FireExplosion(pwrVal, currentPos31, map, 0.4f);
                                }
                            }
                        }
                        catch
                        {
                            this.pos31Flagw = false;
                        }
                    }
                    //4
                    if (pos4Flag && pos4Flagw)
                    {
                        currentPos4 = GetNewPos(currentPos4, origin.x <= target.x, origin.z <= target.z, this.age >= (((duration + pos4Age) / 2)), posx4weight, posz4weight, xProb, 1 - xProb);
                        try
                        {
                            if ((currentPos4.GetTerrain(base.Map).passability == Traversability.Impassable) || !currentPos4.Walkable(base.Map))
                            {
                                this.pos4Flagw = false;
                            }
                            else
                            {
                                if (verVal >= 3)
                                {
                                    this.FireExplosion(pwrVal, currentPos4, map, 0.8f);
                                }
                                else
                                {
                                    this.FireExplosion(pwrVal, currentPos4, map, 0.4f);
                                }
                            }
                        }
                        catch
                        {
                            this.pos4Flagw = false;
                        }
                    }
                    //5
                    if (pos5Flag && pos5Flagw)
                    {
                        currentPos5 = GetNewPos(currentPos5, origin.x <= target.x, origin.z <= target.z, this.age >= (((duration + pos5Age) / 2)), posx5weight, posz5weight, xProb, 1 - xProb);
                        try
                        {
                            if ((currentPos5.GetTerrain(base.Map).passability == Traversability.Impassable) || !currentPos5.Walkable(base.Map))
                            {
                                this.pos5Flagw = false;
                            }
                            else
                            {
                                if (verVal >= 3)
                                {
                                    this.FireExplosion(pwrVal, currentPos5, map, 0.8f);
                                }
                                else
                                {
                                    this.FireExplosion(pwrVal, currentPos5, map, 0.4f);
                                }
                            }
                        }
                        catch
                        {
                            this.pos5Flagw = false;
                        }
                    }
                    //for (int i=0; i < j; i++)
                    //{
                    //    if (i == 10)
                    //    {
                    //        currentPos[i] = GetNewPos(currentPos[i], origin.x <= target.x, origin.z <= target.z, this.age >= (((duration - posAge[i]) / 2) + duration), 0, 0, xProb, 1-xProb);
                    //    }
                    //    else if (i < 3)
                    //    {
                    //        currentPos[i] = GetNewPos(currentPos[i], origin.x <= target.x, origin.z <= target.z, this.age >= (((duration - posAge[i]) / 2) + duration), posxWeight[i] * 3, poszWeight[i]*3, xProb, 1 - xProb);
                    //    }
                    //    else
                    //    {
                    //        currentPos[i] = GetNewPos(currentPos[i], origin.x <= target.x, origin.z <= target.z, this.age >= (((duration - posAge[i]) / 2) + duration), posxWeight[i] * 5, poszWeight[i] * 5, xProb, 1 - xProb);
                    //    }
                    //    this.FireExplosion(currentPos[i], map, 0.4f);
                    //    this.lastStrike = this.age;
                    //}

                    bool flag1 = this.age <= this.duration;
                    if (!flag1)
                    {
                        this.primed = false;
                        return;
                    }
                }
            }
        }
 public void SmoothLerp(GameObject gobject, Vector3 start, Vector3 goal, float alpha, CutsceneLerps WhichLerp)
 {
     if (WhichLerp == CutsceneLerps.slowfastslow)
     {
         gobject.transform.position = Vector3.Lerp(start, goal, 0.5f * Mathf.Sin(Mathf.PI * alpha - Mathf.PI / 2.0f) + 0.5f);
     }
     else if (WhichLerp == CutsceneLerps.fastslow)
     {
         gobject.transform.position = Vector3.Lerp(start, goal, Mathf.Sin(0.5f * Mathf.PI * alpha));
     }
     else if (WhichLerp == CutsceneLerps.slowfast)
     {
         gobject.transform.position = Vector3.Lerp(start, goal, Mathf.Sin(0.5f * (Mathf.PI * alpha - Mathf.PI)) + 1.0f);
     }
     else if (WhichLerp == CutsceneLerps.fastslowfast)
     {
         gobject.transform.position = Vector3.Lerp(start, goal, (1.0f / Mathf.PI) * Mathf.Asin(2.0f * alpha - 1.0f) + 0.5f);
     }
     else if (WhichLerp == CutsceneLerps.normal)
     {
         gobject.transform.position = Vector3.Lerp(start, goal, alpha);
     }
 }
        // Simplifield Moon Calculation [In v3 complete calculations]
        Vector3 ComputeMoonCoords()
        {
            Vector3 result;

            #region Sun Orbital Elements.
            // Sun orbital elements.
            // float ws = SunOrbitalElemtents.w;
            // float es = SunOrbitalElemtents.e;
            //float Ms = SunOrbitalElements.M;
            //float Ms_Rad = Mathf.Deg2Rad * Ms;
            #endregion

            #region Orbital Elements.

            //	OrbitalElements orbitalElements = new OrbitalElements()

            float N = 125.1228f - 0.0529538083f * TimeScale;
            float i = 5.1454f;
            float w = 318.0634f + 0.1643573223f * TimeScale;
            float a = 60.2666f;
            float e = 0.054900f;
            float M = 115.3654f + 13.0649929509f * TimeScale;

            N = Rev(N);
            w = Rev(w);
            M = Rev(M);

            // Orbital elements in radians.
            float N_Rad = Mathf.Deg2Rad * N;
            float i_Rad = Mathf.Deg2Rad * i;
            float M_Rad = Mathf.Deg2Rad * M;

            #endregion


            #region Eccentric Anomaly.
            float E = M + Mathf.Rad2Deg * e * Mathf.Sin(M_Rad) *
                      (1 + e * Mathf.Cos(M_Rad));

            // E in radians
            float E_Rad = Mathf.Deg2Rad * E;
            #endregion

            #region Rectangular Coordinates.
            // Rectangular coordinates of the sun in the plane of the ecliptic.

            float xv = a * (Mathf.Cos(E_Rad) - e);                                        //Debug.Log(xv);
            float yv = a * (Mathf.Sin(E_Rad) * Mathf.Sqrt(1 - e * e)) * Mathf.Sin(E_Rad); //Debug.Log(yv);

            // Convert to distance and true anomaly(r = radians, v = degrees).
            float r = Mathf.Sqrt(xv * xv + yv * yv);             //Debug.Log(r);
            float v = Mathf.Rad2Deg * Mathf.Atan2(yv, xv);       //Debug.Log(v);

            v = Rev(v);

            // longitude in radians.
            float l = Mathf.Deg2Rad * (v + w);

            float Cos_l     = Mathf.Cos(l);
            float Sin_l     = Mathf.Sin(l);
            float Cos_N_Rad = Mathf.Cos(N_Rad);
            float Sin_N_Rad = Mathf.Sin(N_Rad);
            float Cos_i_Rad = Mathf.Cos(i_Rad);

            float xeclip = r * (Cos_N_Rad * Cos_l - Sin_N_Rad * Sin_l * Cos_i_Rad);
            float yeclip = r * (Sin_N_Rad * Cos_l + Cos_N_Rad * Sin_l * Cos_i_Rad);
            float zeclip = r * (Sin_l * Mathf.Sin(i_Rad));

            #endregion

            #region Geocentric Coordinates.

            // Geocentric position for the moon and Heliocentric position for the planets.
            float lonecl = Mathf.Rad2Deg * Mathf.Atan2(yeclip, xeclip);

            lonecl = Rev(lonecl);                                                                              //Debug.Log(lonecl);

            float latecl = Mathf.Rad2Deg * Mathf.Atan2(zeclip, Mathf.Sqrt(xeclip * xeclip + yeclip * yeclip)); //Debug.Log(latecl);

            // True sun longitude.
            float lonSun = m_TrueSunLongitude;

            // Ecliptic longitude and latitude in radians.
            float lonecl_Rad = Mathf.Deg2Rad * lonecl;
            float latecl_Rad = Mathf.Deg2Rad * latecl;

            float nr = 1.0f;
            float xh = nr * Mathf.Cos(lonecl_Rad) * Mathf.Cos(latecl_Rad);
            float yh = nr * Mathf.Sin(lonecl_Rad) * Mathf.Cos(latecl_Rad);
            float zh = nr * Mathf.Sin(latecl_Rad);

            // Geocentric posisition.
            float xs = 0.0f;
            float ys = 0.0f;

            // Convert the geocentric position to heliocentric position.
            float xg = xh + xs;
            float yg = yh + ys;
            float zg = zh;

            #endregion

            #region Equatorial Coordinates.

            // Convert xg, yg in equatorial coordinates.
            float oblecl_Cos = Mathf.Cos(Oblecl);
            float oblecl_Sin = Mathf.Sin(Oblecl);

            float xe = xg;
            float ye = yg * oblecl_Cos - zg * oblecl_Sin;
            float ze = yg * oblecl_Sin + zg * oblecl_Cos;

            #endregion

            #region Ascension, Declination And Hour Angle.

            // Right ascension.
            float RA = Mathf.Rad2Deg * Mathf.Atan2(ye, xe);
            RA = Rev(RA);             //Debug.Log(RA);

            // Declination.
            float Decl = Mathf.Rad2Deg * Mathf.Atan2(ze, Mathf.Sqrt(xe * xe + ye * ye));

            // Declination in radians.
            float Decl_Rad = Mathf.Deg2Rad * Decl;

            // Hour angle.
            float HA = (m_SideralTime * 15) - RA;

            HA = Rev(HA);             //Debug.Log(HA);

            // Hour angle in radians.
            float HA_Rad = Mathf.Deg2Rad * HA;

            #endregion

            #region Declination in rectangular coordinates.

            // HA y Decl in rectangular coordinates.
            float Decl_Cos = Mathf.Cos(Decl_Rad);
            float xr       = Mathf.Cos(HA_Rad) * Decl_Cos;
            float yr       = Mathf.Sin(HA_Rad) * Decl_Cos;
            float zr       = Mathf.Sin(Decl_Rad);

            // Rotate the rectangualar coordinates system along of the Y axis(radians).
            float sinLatitude = Mathf.Sin(Latitude_Rad);
            float cosLatitude = Mathf.Cos(Latitude_Rad);

            float xhor = xr * sinLatitude - zr * cosLatitude;
            float yhor = yr;
            float zhor = xr * cosLatitude + zr * sinLatitude;
            #endregion

            #region Azimuth, Altitude And Zenith[Radians].
            result.x = Mathf.Atan2(yhor, xhor) + Mathf.PI;
            result.y = Mathf.Asin(zhor);
            result.z = k_HalfPI - result.y;
            #endregion

            return(result);
        }
Beispiel #6
0
        private static void CreateUV(ref MeshData m, UVMode uvMode)
        {
            for (int i = 0; i < m.UV.Count; i++)
            {
                Vector3 n = m.Normals[i];
                Vector2 textureCoordinates = new Vector2();

                switch (uvMode)
                {
                case UVMode.Sphere:
                {
                    textureCoordinates.x = Mathf.Atan2(n.x, n.z) / (-2f * Mathf.PI);
                    textureCoordinates.y = Mathf.Asin(n.y) / Mathf.PI + 0.5f;
                }
                break;

                case UVMode.Panorama:
                {
                    textureCoordinates.x = Mathf.Atan2(n.x, n.z) / (-2f * Mathf.PI);
                    textureCoordinates.y = Mathf.Clamp(n.y, 0.0f, 1.0f);
                }
                break;

                case UVMode.PanoramaMirrorDown:
                {
                    textureCoordinates.x = Mathf.Atan2(n.x, n.z) / (-2f * Mathf.PI);
                    textureCoordinates.y = Mathf.Abs(n.y);
                }
                break;

                case UVMode.Dome:
                {
                    float y   = (n.y < 0.0f ? 0.0f : n.y);
                    float r   = Mathf.Atan2(Mathf.Sqrt(n.x * n.x + n.z * n.z), y) / Mathf.PI;
                    float phi = Mathf.Atan2(n.z, n.x);
                    textureCoordinates.x = (r * Mathf.Cos(phi)) + 0.5f;
                    textureCoordinates.y = (r * Mathf.Sin(phi)) + 0.5f;
                }
                break;

                case UVMode.DomeMirrorDown:
                {
                    float y   = Math.Abs(n.y);
                    float r   = Mathf.Atan2(Mathf.Sqrt(n.x * n.x + n.z * n.z), y) / Mathf.PI;
                    float phi = Mathf.Atan2(n.z, n.x);
                    textureCoordinates.x = (r * Mathf.Cos(phi)) + 0.5f;
                    textureCoordinates.y = (r * Mathf.Sin(phi)) + 0.5f;
                }
                break;

                case UVMode.DomeDouble:
                {
                    float y   = Math.Abs(n.y);
                    float r   = Mathf.Atan2(Mathf.Sqrt(n.x * n.x + n.z * n.z), y) / Mathf.PI;
                    float phi = Mathf.Atan2(n.z, n.x);
                    textureCoordinates.x = (r * Mathf.Cos(phi)) + 0.5f;
                    textureCoordinates.y = (r * Mathf.Sin(phi)) + 0.5f;
                    if (n.y >= 0.0f)
                    {
                        textureCoordinates.x = (textureCoordinates.x + 1.0f) * 0.5f;
                    }
                    else
                    {
                        textureCoordinates.x *= 0.5f;
                    }
                }
                break;

                case UVMode.FishEyeMirrored:
                {
                    float z   = Math.Abs(n.z);
                    float r   = Mathf.Atan2(Mathf.Sqrt(n.x * n.x + n.y * n.y), z) / Mathf.PI;
                    float phi = Mathf.Atan2(n.y, n.x);
                    textureCoordinates.x = (r * Mathf.Cos(phi)) + 0.5f;
                    textureCoordinates.y = (r * Mathf.Sin(phi)) + 0.5f;
                }
                break;

                case UVMode.FishEye360:
                {
                    float r = Mathf.Atan2(Mathf.Sqrt(n.x * n.x + n.y * n.y), n.z) / (Mathf.PI * 2.0f);

                    // TODO: The fish eye gets distorted at these coordinates, not sure if this is fixable or not...

                    /*
                     * const float t = 0.35f;
                     * if (n.x >= -t && n.x <= t && n.y >= -t && n.y <= t)
                     * {
                     *  //Debug.LogFormat("BOO: n={0}, t={1}, r={2}, phi={3}", n, textureCoordinates, r, phi);
                     *  //textureCoordinates.x = 0.0f;
                     *  //textureCoordinates.y = 0.0f;
                     * }
                     */

                    float phi = Mathf.Atan2(n.y, n.x);
                    textureCoordinates.x = (r * Mathf.Cos(phi)) + 0.5f;
                    textureCoordinates.y = (r * Mathf.Sin(phi)) + 0.5f;
                }
                break;

                default: throw new ArgumentException("Invalid uv mode: " + uvMode);
                }

                textureCoordinates.x = WrapFloat(textureCoordinates.x);
                textureCoordinates.y = WrapFloat(textureCoordinates.y);
                m.UV[i] = textureCoordinates;
            }
        }
 public static float Safe_Asin(float r)
 {
     return(Mathf.Asin(Mathf.Min(1.0f, Mathf.Max(-1.0f, r))));
 }
Beispiel #8
0
    public void lookAt(Vector3 position)
    {
        if (enemyLockOn)
        {
            float angle;

            float _vertical = position.y > transform.position.y ? Mathf.Abs(position.y - transform.position.y) : Mathf.Abs(transform.position.y - position.y);
            bool  above     = position.y > transform.position.y;
            // calculates the vertical displacement between the player and targeted enemy

            float _horizontal = position.x > transform.position.x ? Mathf.Abs(position.x - transform.position.x) : Mathf.Abs(transform.position.x - position.x);
            bool  toRight     = position.x > transform.position.x;
            // calculates the horizontal displacement between the player and targeted enemy

            float _hypotenuse = Mathf.Sqrt((_vertical * _vertical) + (_horizontal * _horizontal));
            // calculates the hypotenuse between the player and targeted enemy based on the vertical and horizontal displacements previously calculated

            if (_vertical > _horizontal)
            {
                angle = Mathf.Asin(_horizontal / _hypotenuse) * (180 / Mathf.PI);
            }
            else
            {
                angle = Mathf.Asin(_vertical / _hypotenuse) * (180 / Mathf.PI);
            }
            // the angle is calculated based on whether or not the vertical displacement vector is larger than the horizontal
            // pseudo-code: if vertical is larger -> use the horizontal displacement in equation, otherwise use the vertical displacement

            // this corrects the angle at which the shield rotates due to how the angle is initially calculated (I have to tell the code which
            // portions of which quadrant the enemy is in so that it rotates accordingly).
            // origin is the player's position
            if (above && toRight)
            {
                // 1st quadrant
                if (_horizontal > _vertical)
                {
                    angle -= 90;
                }
                else
                {
                    angle -= angle * 2;
                }
            }
            else if (above && !toRight)
            {
                // 2nd quadrant
                if (_horizontal > _vertical)
                {
                    angle = 90 - angle;
                }
            }
            else if (!above && !toRight)
            {
                // third quadrant
                if (_horizontal > _vertical)
                {
                    angle += 90;
                }
                else
                {
                    angle += (90 - angle) * 2;
                }
            }
            else if (!above && toRight)
            {
                // fourth quadrant
                if (_horizontal > _vertical)
                {
                    angle -= angle * 2;
                    angle -= 90;
                }
                else
                {
                    angle -= 180;
                }
            }

            transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(0, 0, angle), 10 * Time.deltaTime);
        }
        else
        {
            position.x = (position.x / Screen.width) * 512;
            position.y = (position.y / Screen.height) * 288;
            // due to pixel perfect-ification, the mouse position gets all whack so I have to correct it
            // divide position components by screen width and height -> multiply by intended width and height respectively

            mousePosition = position;
            mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);

            //transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(transform.position - mousePosition, Vector3.forward), 10 * Time.deltaTime);
            // smoothly interpolates between mouse position and current rotation. (maybe incorporate that into transitioning from target to mouse position
            // so it's not so snappy?
            Quaternion targetRotation = Quaternion.Euler(0.0f, 0.0f, Quaternion.LookRotation(transform.position - mousePosition, Vector3.forward).eulerAngles.z);
            transform.rotation = targetRotation;
        }
    }
Beispiel #9
0
    public void Walk(Vector3 direction)
    {
        direction.y = 0;

        direction.Normalize();

        //get the floor the player is colliding with

        Transform TheFloor    = Globals.transformTable["Floor"] as Transform;
        var       floorscript = TheFloor.GetComponent(typeof(Floor)) as Floor;

        var currentFloorPlayerIsHitting = floorscript.WhatFloorIsColliding(transform);

        //Vector3 SlopeNormal = transform.GetComponent(Jump).SlopeNormal;
        //Vector3 EulerSave = transform.eulerAngles;
        //float angle;
        if (direction.magnitude != 0)
        {
            if (direction.x > 0)
            {
                //Library.UncompoundingLog("direction.x is positive");

                currentAngleOfPlayerQuaternion = -Mathf.Asin(direction.z / direction.magnitude) - Mathf.PI / 2.0f;
            }

            else
            {
                currentAngleOfPlayerQuaternion = Mathf.Asin(direction.z / direction.magnitude) + (Mathf.PI / 2.0f);
            }

            // Library.UncompoundingLog(currentAngleOfPlayerQuaternion);
        }

        if (currentFloorPlayerIsHitting != null)          //if it is hitting a floor



        /*
         *
         * find if the next position can be scaled and move the y position there
         *
         */

        {
            var futureposition = transform.position + direction * floorspeed * Time.deltaTime;

            Ray          ray     = new Ray(futureposition, Vector3.up);
            RaycastHit[] allhits = Physics.RaycastAll(ray);

            foreach (RaycastHit hit in allhits)
            {
                //Debug.Log(transform.GetComponent(Jump).stringifyState());

                if (hit.transform.Equals(currentFloorPlayerIsHitting))                  //if it is the same floor currently stood on

                {
                    Vector3 normal = hit.normal;
                    //get the angle to the FLoor

                    float angle = Library.getAngle(Mathf.Asin(normal.y / normal.magnitude), Mathf.PI * 2, true);
                    //				Debug.Log("Hit: " + hit.point.y + "position: " + futureposition.y + "Subtract: " + (hit.point.y - transform.position.y));

                    //find if the scale is too high

                    //Debug.Log("angle: " + angle.ToString() + " normal: " + Library.getVector(normal));

                    if (angle > (Mathf.PI / 2) + scaleAngle || angle < (Mathf.PI / 2) - scaleAngle)                  //may cause problems from slight deviation of y axis

                    //Debug.Log("too High: " + angle.ToString() + " " + scaleAngle.ToString());



                    {
                        return;
                    }

                    transform.position = hit.point;                    // + transform.GetComponent.<Collider>().bounds.size.y/2; //move the y axis there

                    var x = 0;
                }
            }

            //Debug.Log("Fall");



            transform.position = futureposition;
        }

        else
        {
            //		Debug.Log("Air");

            transform.position += direction * Time.deltaTime * airspeed;
        }
    }
Beispiel #10
0
    void Update()
    {
        //tr.transform.position = new Vector3(Mathf.Sin(Time.time * 1.51f) * 7.0f, Mathf.Cos(Time.time * 1.27f) * 4.0f, 0.0f);
        //timer -= Time.deltaTime();
        distTravelled += Vector3.Distance(transform.position, lastPosition);
        lastPosition   = transform.position;
        //Debug.Log(transform.position);
        //Debug.Log(_navMeshAgent.remainingDistance);
        if (isReturn)
        {
            //Debug.Log("Am in isret");
            //Debug.Log(distTravelled);
            if (distTravelled >= distBetCheckpoints && checkpoints.Count < NumCheckpoints)
            {
                //Vector3 closest = findLowestSlopePoint(transform.position, 3);
                float x = transform.position.x;
                float y = transform.position.y - -1731707;
                float z = transform.position.z;
                float height;
                if (x < 0f && y < 0f && z < 0f)
                {
                    height = Mathf.Pow(x * x + y * y + z * z, .5f) + 1737400;
                }
                else
                {
                    height = -1f * Mathf.Pow(x * x + y * y + z * z, .5f) + 1737400;
                }
                if (x < 0f)
                {
                    height = height * -1f;
                }

                //Debug.Log(height);
                float lat      = (Mathf.Asin(z / (height + 1737400f)));
                float lon      = (Mathf.Acos(y / ((height + 1737400f) * Mathf.Cos(lat))));
                float aziumuth = Mathf.Atan2(Mathf.Sin(-lon), ((Mathf.Cos(lat) * 0) - (Mathf.Sin(lat) * 1 * Mathf.Cos(-lon))));
                float rangeAb  = Mathf.Pow((361000000f - x) * (361000000f - x) + y * y + (-42100000f - z) * (-42100000f - z), .5f);
                float rz       = (361000000f - x) * Mathf.Cos(lat) * Mathf.Cos(lon) + y * Mathf.Cos(lat) * Mathf.Sin(lon) + (-42100000f - z) * Mathf.Sin(lat);
                float elev     = Mathf.Asin(rz / rangeAb);
                lon += -90;
                lat += 54.794f;
                Debug.Log("Checkpoint at: " + transform.position + "\tAzimuth: " + aziumuth + "\tElev: " + elev);
                checkpoints.Add(transform.position);
                resetDist();
            }
        }
        if (firstTime && _navMeshAgent.remainingDistance <= 0.2 && distTravelled > 2)
        {
            tr.emitting = false;
        }
        if (firstTime && _navMeshAgent.remainingDistance == 0 && distTravelled > 2)

        {
            //_navMeshAgent.path = null;
            //_navMeshAgent.isStopped = true;
            //_navMeshAgent.ResetPath();
            //_navMeshAgent.updatePosition = false;
            //this.GetComponent<MeshRenderer>().enabled = false;
            _navMeshAgent.speed = _navMeshAgent.speed * 3;
            // _navMeshAgent.acceleration = 100;
            // _navMeshAgent.angularSpeed = 500;
            firstTime = false;
            Debug.Log("reached destNew");
            totalDist = distTravelled;
            Debug.Log("reached calculating totalDist");
            Debug.Log("TotalDist: " + totalDist + " ; NumCheckpoints: " + NumCheckpoints);
            distBetCheckpoints = totalDist / NumCheckpoints;
            Debug.Log("DBC: " + distBetCheckpoints);
            resetDist();
            Debug.Log("Orig: " + origPosition);

            isReturn = true;
            this.transform.position      = origPosition;
            this.transform.localPosition = origPosition;
            _navMeshAgent.Warp(origPosition);
            _navMeshAgent.updatePosition = true;
            _navMeshAgent.isStopped      = false;
            resetDist();
            _navMeshAgent.ResetPath();
            //setChecks();
            // _navMeshAgent.ResetPath();



            //resetDist();
            Debug.Log("Setting Destination to go again");
            SetDestination(_destination.transform.position);
        }

        /*if(supposedToStay)
         * {
         *  gameObject.transform.localPosition = origPosition;
         * }*/
        //Debug.Log("Distance Left: " + _navMeshAgent.remainingDistance + " Distance went: " + distTravelled);
        //Debug.Log("Remaining: "+_navMeshAgent.remainingDistance+" ; Pos: "+transform.position);
        //Debug.Log(transform.position);
        //Debug.Log("Distance traveled: "+distTravelled);
    }
Beispiel #11
0
 /// <summary>
 /// Get the elevation angle to this vector from a reference point.
 /// </summary>
 /// <param name="position">The vector to find the elevation of.</param>
 /// <param name="center">The reference point.</param>
 /// <param name="up">The normal of the plane to find the elevation from.</param>
 /// <returns>The elevation angle.</returns>
 public static float GetElevation(this Vector3 position, Vector3 center, Vector3 up)
 {
     return(Mathf.Asin(Vector3.Dot((position - center).normalized, up.normalized)) * Mathf.Rad2Deg);
 }
 float VectorToAngle(Vector3 v1, Vector3 v2)
 {
     return(Mathf.Asin(Vector3.Distance(Vector3.zero, Vector3.Cross(v1.normalized, v2.normalized))) * Mathf.Rad2Deg);
 }
    private void Update()
    {
        AxisInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
        if (isSwinging)
        {
            //swing animation control
            if (AxisInput.x < 0)
            {
                transform.eulerAngles = new Vector3(0, 180, -1 * Mathf.Asin((transform.position.x - rope.connectedAnchor.x) / rope.distance) * 180f / Mathf.PI);
                faceingDir            = -1;
            }
            else if (AxisInput.x > 0)
            {
                transform.eulerAngles = new Vector3(0, 0, Mathf.Asin((transform.position.x - rope.connectedAnchor.x) / rope.distance) * 180f / Mathf.PI);
                faceingDir            = 1;
            }
            if (Input.GetAxisRaw("Horizontal") == 0)
            {
                AxisInput.x = 0;
            }
        }
        else
        {
            //moveing animation control
            if (AxisInput.x < 0)
            {
                transform.eulerAngles = new Vector3(0, 180, transform.eulerAngles.z);
                playerAnimator.SetBool("isMoveing", true);
                faceingDir = -1;
            }
            else if (AxisInput.x > 0)
            {
                transform.eulerAngles = new Vector3(0, 0, transform.eulerAngles.z);
                playerAnimator.SetBool("isMoveing", true);
                faceingDir = 1;
            }
            if (Input.GetAxisRaw("Horizontal") == 0)
            {
                AxisInput.x = 0;
                playerAnimator.SetBool("isMoveing", false);
            }

            playerAnimator.SetFloat("speed", AxisInput.x * speed);
        }
        if (Input.GetButtonDown("Jump") && (isGrounded || isSwinging))
        {
            jump();
        }

        if (Input.GetButtonUp("Jump"))
        {
            rb2D.velocity = new Vector2(rb2D.velocity.x, 0f);
        }

        if ((Input.GetKeyDown(KeyCode.X) || Input.GetButtonDown("Fire1")) && Input.GetKey(KeyCode.C) == false)
        {
            throwSpear();
        }

        if (Input.GetKeyDown(KeyCode.C))
        {
            activeShield(true);
            speed *= shieldSpeedToSpeedRatio;
        }
        if (Input.GetKeyUp(KeyCode.C))
        {
            activeShield(false);
            speed /= shieldSpeedToSpeedRatio;
        }
        if (Input.GetKeyDown(KeyCode.Z) && isGrounded == false && isSwinging == false)
        {
            throwHook();
        }
        Debug.DrawLine(transform.position, hook.GetComponent <GraplingHook>().nearestGrabPlace.transform.position);
    }
Beispiel #14
0
    float applyMoves(int[] moves, int x, int y)
    {
        float colorValue = 1;

        for (int i = 0; i < moves.Length; i++)
        {
            switch (moves[i])
            {
            case (0):            //Addition X
            default:
                colorValue += x;
                break;

            case (1):            //Addition Y
                colorValue += y;
                break;

            case (2):           //Subtraction X
                colorValue -= x;
                break;

            case (3):           //Subtraction Y
                colorValue -= y;
                break;

            case (4):           //Multiplcation X
                colorValue *= x;
                break;

            case (5):           //Multiplcation Y
                colorValue *= y;
                break;

            case (6):           //Division X
                if (colorValue == 0)
                {
                    colorValue++;
                }
                colorValue /= x;
                break;

            case (7):           //Multiplcation Y
                if (colorValue == 0)
                {
                    colorValue++;
                }
                colorValue /= y;
                break;

            case (8):           //Modulus X
                if (x == 0)
                {
                    colorValue = 0;
                }
                else
                {
                    colorValue = Mathf.Abs(colorValue) % x;
                }
                break;

            case (9):           //Modulus Y
                if (y == 0)
                {
                    colorValue = 0;
                }
                else
                {
                    colorValue = Mathf.Abs(colorValue) % y;
                }
                break;

            case (10):           //Power X
                colorValue = (int)Mathf.Pow(colorValue, x);
                break;

            case (11):           //Power Y
                colorValue = (int)Mathf.Pow(colorValue, y);
                break;

            case (12):           //Pi
                colorValue *= Mathf.PI;
                break;

            case (13):           //Pi FLEX
                colorValue *= Mathf.Pow(Mathf.PI, 2);
                break;

            case (14):           // Square Root
                colorValue = Mathf.Sqrt(colorValue);
                break;

            case (15):           // Square Root FLEX
                colorValue = Mathf.Sqrt(colorValue * x * y);
                break;

            case (16):
                colorValue = Mathf.Sin(colorValue);
                break;

            case (17):
                colorValue = Mathf.Asin(colorValue);
                break;

            case (18):
                colorValue = Mathf.Cos(colorValue);
                break;

            case (19):
                colorValue = Mathf.Acos(colorValue);
                break;

            case (20):
                colorValue = Mathf.Tan(colorValue);
                break;

            case (21):
                colorValue = Mathf.Atan(colorValue);
                break;

            case (22):
                colorValue = Mathf.Log(colorValue);
                break;

            case (23):
                colorValue = Mathf.Exp(colorValue);
                break;
            }
        }

        colorValue %= 256;

        float finalValue = (float)colorValue / 256;

        return(finalValue);
    }
Beispiel #15
0
        private static float GetDivideLine(PlanetFactory factory, PlayerAction_Build actionBuild, List <int> objectIds)
        {
            if (objectIds.Count == 0)
            {
                return(-Mathf.PI);
            }

            _divideline_marks ??= new bool[1001];
            Array.Clear(_divideline_marks, 0, 1001);

            int segment = 200;

            if (factory.planet.aux.activeGrid != null)
            {
                segment = factory.planet.aux.activeGrid.segment;
            }

            const double divisor = 2 * Mathf.PI / 1000;

            foreach (int objId in objectIds)
            {
                if (actionBuild.noneTool.GetPrefabDesc(objId) != null)
                {
                    Vector3 position     = actionBuild.noneTool.GetObjectPose(objId).position.normalized;
                    float   latitudeRad  = Mathf.Asin(position.y);
                    float   longitudeRad = Mathf.Atan2(position.x, -position.z);

                    int longitudeSegmentCount = BlueprintUtils.GetLongitudeSegmentCount(latitudeRad, segment);
                    int latGrid  = Mathf.CeilToInt((Mathf.CeilToInt((float)segment / longitudeSegmentCount) - 1) * 0.5f);
                    int longGrid = (int)Math.Round((longitudeRad + Mathf.PI) / divisor);

                    for (int i = -latGrid; i <= latGrid; i++)
                    {
                        int index = (int)Mathf.Repeat(longGrid + i, 1000f);
                        _divideline_marks[index] = true;
                    }
                }
            }

            int gridx1   = -1;
            int gridy1   = -1;
            int gridx2   = -1;
            int grixy2   = -1;
            int gridPos2 = 0;

            for (int j = 0; j < 1001; j++)
            {
                if (_divideline_marks[j])
                {
                    if (gridx2 == -1)
                    {
                        gridx2 = j;
                        gridx1 = j;
                        gridy1 = j;
                    }
                    else
                    {
                        int num11 = j - gridx2;
                        if (num11 > gridPos2)
                        {
                            grixy2   = gridx2;
                            gridPos2 = num11;
                        }

                        gridx2 = j;
                        gridy1 = j;
                    }
                }
            }

            int gridPos1 = gridx1 + 1000 - gridy1;

            if (gridPos1 > gridPos2)
            {
                int gridPos = gridy1 + gridPos1 / 2;
                return(Mathf.Repeat((float)(gridPos * divisor), 2 * Mathf.PI) - Mathf.PI);
            }

            gridPos2 = grixy2 + gridPos2 / 2;
            return((float)(gridPos2 * divisor - Mathf.PI));
        }
Beispiel #16
0
    // Update is called once per frame
    void Update()
    {
        Rigidbody rb = GetComponent <Rigidbody>();

        if (Input.GetAxis("Player" + playerNum + "_Acceleration") > 0)
        {
            if (direction.z == 1)
            {
                rb.AddForce(transform.forward * Input.GetAxis("Player" + playerNum + "_Acceleration") * accelerationMod, ForceMode.Force);
            }
            if (direction.z == -1)
            {
                rb.AddForce(transform.forward * -1 * Input.GetAxis("Player" + playerNum + "_Acceleration") * accelerationMod, ForceMode.Force);
            }
            if (direction.y == 1)
            {
                rb.AddForce(transform.up * Input.GetAxis("Player" + playerNum + "_Acceleration") * accelerationMod, ForceMode.Force);
            }
            if (direction.y == -1)
            {
                rb.AddForce(transform.up * -1 * Input.GetAxis("Player" + playerNum + "_Acceleration") * accelerationMod, ForceMode.Force);
            }
            if (direction.x == 1)
            {
                rb.AddForce(transform.right * Input.GetAxis("Player" + playerNum + "_Acceleration") * accelerationMod, ForceMode.Force);
            }
            if (direction.x == -1)
            {
                rb.AddForce(transform.right * -1 * Input.GetAxis("Player" + playerNum + "_Acceleration") * accelerationMod, ForceMode.Force);
            }
        }

        Vector2 joyPos = new Vector2(Mathf.Rad2Deg * Mathf.Asin(Input.GetAxis("Player" + playerNum + "_Horizontal")), Mathf.Rad2Deg * Mathf.Asin(Input.GetAxis("Player" + playerNum + "_Vertical")));

        shipAngle = transform.rotation.eulerAngles.y % 360 + 360;



        if (joyPos.magnitude > joystickMovementThreshold)
        {
            joyAngle = (-1 * Mathf.Rad2Deg * Mathf.Atan2(joyPos.x, joyPos.y) + 180 + rotOffSet) % 360 + 360;

            float differenceAngle = Mathf.Abs(shipAngle - joyAngle);

            Debug.Log(joyAngle + " " + shipAngle);

            if (differenceAngle > degreeJitterReduce && differenceAngle < 360 - degreeJitterReduce)
            {
                if ((joyAngle - shipAngle + 360) % 360 > 180)
                {
                    rb.angularVelocity = new Vector3(0, Mathf.Clamp(-RotateSpeed * differenceAngle * 0.1f, -RotateSpeed, 0), 0);
                }
                else if (((joyAngle - shipAngle + 360) % 360 < 180))
                {
                    rb.angularVelocity = new Vector3(0, Mathf.Clamp(RotateSpeed * differenceAngle * 0.1f, 0, RotateSpeed), 0);
                }
                else
                {
                    rb.angularVelocity = new Vector3(0, 0, 0);
                }
                //Rigidbody rb = GetComponent<Rigidbody>();
                // rb.angularVelocity = new Vector3(rb.angularVelocity.x, Mathf.Clamp(transform.rotation.eulerAngles.y - joyAngle, -maxAngularVelY, maxAngularVelY), rb.angularVelocity.z);
            }
            else
            {
                rb.angularVelocity = new Vector3(0, 0, 0);
            }
        }
        else
        {
            rb.angularVelocity = new Vector3(0, 0, 0);
        }
    }
Beispiel #17
0
    public static float Ease(EasingType type, float t, float b, float c, float d)
    {
        switch (type)
        {
        case EasingType.easeLinear:
        {
            return(c * t / d + b);
        }

        case EasingType.easeSwing:
        {
            return(-c * (t /= d) * (t - 2f) + b);
        }

        case EasingType.easeInQuad:
        {
            return(c * (t /= d) * t + b);
        }

        case EasingType.easeOutQuad:
        {
            return(-c * (t /= d) * (t - 2) + b);
        }

        case EasingType.easeInOutQuad:
        {
            if ((t /= d / 2) < 1)
            {
                return(c / 2 * t * t + b);
            }
            return(-c / 2 * ((--t) * (t - 2) - 1) + b);
        }

        case EasingType.easeInCubic:
        {
            return(c * (t /= d) * t * t + b);
        }

        case EasingType.easeOutCubic:
        {
            return(c * ((t = t / d - 1) * t * t + 1) + b);
        }

        case EasingType.easeInOutCubic:
        {
            if ((t /= d / 2) < 1)
            {
                return(c / 2 * t * t * t + b);
            }
            return(c / 2 * ((t -= 2) * t * t + 2) + b);
        }


        case EasingType.easeInQuart:
        {
            return(c * (t /= d) * t * t * t + b);
        }

        case EasingType.easeOutQuart:
        {
            return(-c * ((t = t / d - 1) * t * t * t - 1) + b);
        }

        case EasingType.easeInOutQuart:
        {
            if ((t /= d / 2) < 1)
            {
                return(c / 2 * t * t * t * t + b);
            }
            return(-c / 2 * ((t -= 2) * t * t * t - 2) + b);
        }

        case EasingType.easeInQuint:
        {
            return(c * (t /= d) * t * t * t * t + b);
        }

        case EasingType.easeOutQuint:
        {
            return(c * ((t = t / d - 1) * t * t * t * t + 1) + b);
        }

        case EasingType.easeInOutQuint:
        {
            if ((t /= d / 2) < 1)
            {
                return(c / 2 * t * t * t * t * t + b);
            }
            return(c / 2 * ((t -= 2) * t * t * t * t + 2) + b);
        }

        case EasingType.easeInSine:
        {
            return(-c *Mathf.Cos(t / d *(Mathf.PI / 2)) + c + b);
        }

        case EasingType.easeOutSine:
        {
            return(c * Mathf.Sin(t / d * (Mathf.PI / 2)) + b);
        }

        case EasingType.easeInOutSine:
        {
            return(-c / 2 * (Mathf.Cos(Mathf.PI * t / d) - 1) + b);
        }

        case EasingType.easeInExpo:
        {
            return((t == 0) ? b : c *Mathf.Pow(2, 10 *(t / d - 1)) + b);
        }

        case EasingType.easeOutExpo:
        {
            return((t == d) ? b + c : c *(-Mathf.Pow(2, -10 * t / d) + 1) + b);
        }

        case EasingType.easeInOutExpo:
        {
            if (t == 0)
            {
                return(b);
            }
            if (t == d)
            {
                return(b + c);
            }
            if ((t /= d / 2) < 1)
            {
                return(c / 2 * Mathf.Pow(2, 10 * (t - 1)) + b);
            }
            return(c / 2 * (-Mathf.Pow(2, -10 * --t) + 2) + b);
        }

        case EasingType.easeInCirc:
        {
            return(-c * (Mathf.Sqrt(1 - (t /= d) * t) - 1) + b);
        }

        case EasingType.easeOutCirc:
        {
            return(c * Mathf.Sqrt(1 - (t = t / d - 1) * t) + b);
        }

        case EasingType.easeInOutCirc:
        {
            if ((t /= d / 2) < 1)
            {
                return(-c / 2 * (Mathf.Sqrt(1 - t * t) - 1) + b);
            }
            return(c / 2 * (Mathf.Sqrt(1 - (t -= 2) * t) + 1) + b);
        }

        case EasingType.easeInBack:
        {
            float s = 1.70158f;
            return(c * (t /= d) * t * ((s + 1f) * t - s) + b);
        }

        case EasingType.easeOutBack:
        {
            float s = 1.70158f;
            return(c * ((t = t / d - 1f) * t * ((s + 1f) * t + s) + 1f) + b);
        }

        case EasingType.easeInOutBack:
        {
            float s = 1.70158f;
            if ((t /= d / 2f) < 1f)
            {
                return(c / 2f * (t * t * (((s *= (1.525f)) + 1f) * t - s)) + b);
            }
            return(c / 2f * ((t -= 2f) * t * (((s *= (1.525f)) + 1f) * t + s) + 2f) + b);
        }

        case EasingType.easeInBounce:
        {
            return(c - Ease(EasingType.easeOutBounce, d - t, 0f, c, d) + b);
        }

        case EasingType.easeOutBounce:
        {
            if ((t /= d) < (1f / 2.75f))
            {
                return(c * (7.5625f * t * t) + b);
            }
            else if (t < (2f / 2.75f))
            {
                return(c * (7.5625f * (t -= (1.5f / 2.75f)) * t + .75f) + b);
            }
            else if (t < (2.5f / 2.75f))
            {
                return(c * (7.5625f * (t -= (2.25f / 2.75f)) * t + .9375f) + b);
            }
            else
            {
                return(c * (7.5625f * (t -= (2.625f / 2.75f)) * t + .984375f) + b);
            }
        }

        case EasingType.easeInOutBounce:
        {
            if (t < d / 2f)
            {
                return(Ease(EasingType.easeInBounce, t * 2f, 0f, c, d) * .5f + b);
            }
            return(Ease(EasingType.easeOutBounce, t * 2f - d, 0f, c, d) * .5f + c * .5f + b);
        }

        case EasingType.easeInElastic:
        {
            float s = 1.70158f; float p = 0f; float a = c;
            if (t == 0f)
            {
                return(b);
            }
            if ((t /= d) == 1f)
            {
                return(b + c);
            }
            if (p == 0f)
            {
                p = d * .3f;
            }
            if (a < Mathf.Abs(c))
            {
                a = c; s = p / 4f;
            }
            else
            {
                s = p / (2f * Mathf.PI) * Mathf.Asin(c / a);
            }
            if (float.IsNaN(s))
            {
                s = 0f;
            }
            return(-(a * Mathf.Pow(2f, 10f * (t -= 1f)) * Mathf.Sin((t * d - s) * (2f * Mathf.PI) / p)) + b);
        }

        case EasingType.easeOutElastic:
        {
            float s = 1.70158f; float p = 0f; float a = c;
            if (t == 0f)
            {
                return(b);
            }
            if ((t /= d) == 1f)
            {
                return(b + c);
            }
            if (p == 0f)
            {
                p = d * .3f;
            }
            if (a < Mathf.Abs(c))
            {
                a = c; s = p / 4f;
            }
            else
            {
                s = p / (2f * Mathf.PI) * Mathf.Asin(c / a);
            }
            if (float.IsNaN(s))
            {
                s = 0f;
            }
            return(a * Mathf.Pow(2f, -10f * t) * Mathf.Sin((t * d - s) * (2f * Mathf.PI) / p) + c + b);
        }

        case EasingType.easeInOutElastic:
        {
            float s = 1.70158f; float p = 0f; float a = c;
            if (t == 0f)
            {
                return(b);
            }
            if ((t /= d / 2f) == 2f)
            {
                return(b + c);
            }
            if (p == 0f)
            {
                p = d * (.3f * 1.5f);
            }
            if (a < Mathf.Abs(c))
            {
                a = c; s = p / 4f;
            }
            else
            {
                s = p / (2f * Mathf.PI) * Mathf.Asin(c / a);
            }
            if (float.IsNaN(s))
            {
                s = 0f;
            }
            if (t < 1f)
            {
                return(-.5f * (a * Mathf.Pow(2f, 10f * (t -= 1f)) * Mathf.Sin((t * d - s) * (2f * Mathf.PI) / p)) + b);
            }
            return(a * Mathf.Pow(2f, -10f * (t -= 1f)) * Mathf.Sin((t * d - s) * (2f * Mathf.PI) / p) * .5f + c + b);
        }
        }

        // Default linear
        return(c * t / d + b);
    }
Beispiel #18
0
    void addLineSegmentIgnoreDist(Vector3 end)
    {
        float dist = Vector3.Distance(oldPos, end);

        positions.Add(end);
        lr.positionCount = positions.Count + 1;

        averagePos = new Vector3(0, 0, 0);
        for (int i = positions.Count - 1; i != -1; i--)
        {
            averagePos += positions[i] / positions.Count;
        }

        GameObject coll = new GameObject("colliderBoi");

        coll.transform.parent = this.gameObject.transform;
        colliders.Add(coll);
        BoxCollider boxCollider = coll.AddComponent <BoxCollider>();

        coll.transform.localPosition = (oldPos + end) / 2;     // + new Vector3(0, width, width)/2;
        float hieght = (end - oldPos).y;
        float depth  = (end - oldPos).z;
        float widthh = (end - oldPos).x;
        int   mult   = 1;
        int   multz  = -1;

        if (((hieght > 0) == true && (depth > 0) == true && (widthh > 0) == true))
        {
            mult  = -1;
            multz = 1;
        }
        else if (((hieght > 0) == false && (depth > 0) == true && (widthh > 0) == true))
        {
            mult  = -1;
            multz = 1;
        }
        else if (((hieght > 0) == true && (depth > 0) == false && (widthh > 0) == true))
        {
            mult  = -1;
            multz = 1;
        }
        else if (((hieght > 0) == false && (depth > 0) == false && (widthh > 0) == true))
        {
            mult  = -1;
            multz = 1;
        }



        float xRot = Mathf.Rad2Deg * Mathf.Asin(widthh / dist);
        float yRot;

        if (depth != 0)
        {
            yRot = Mathf.Rad2Deg * Mathf.Asin(depth / Mathf.Sqrt(Mathf.Pow(widthh, 2) + Mathf.Pow(depth, 2)));
        }
        else
        {
            yRot = 0;
        }
        float zRot = Mathf.Rad2Deg * Mathf.Asin(hieght / dist);

        coll.transform.localRotation = Quaternion.Euler(0, mult * yRot, multz * zRot);     //
        boxCollider.size             = new Vector3(dist, width, width);
        oldPos = end;
        pointNum++;

        lr.SetPosition(pointNum, end);
    }
Beispiel #19
0
    private void View()
    {
        //获得在ViewRange的物体
        List <Collider2D> targets = new List <Collider2D>();
        ContactFilter2D   vf      = new ContactFilter2D().NoFilter(); //过滤器

        vf.SetLayerMask(ViewLayer);
        vf.useLayerMask = true;
        vf.useTriggers  = true;
        //Debug.Log(LayerMask.LayerToName(vm));
        ViewRange.OverlapCollider(vf, targets);

        //Debug.Log(ViewRange.OverlapCollider(vf, targets));

        //遍历
        foreach (Collider2D c in targets)
        {
            if (c == null)
            {
                continue;
            }
            SensoryVisual sv;
            //检测到SensoryVisual脚本的才是可视对象
            if ((sv = c.gameObject.GetComponent <SensoryVisual>()) == null)
            {
                //Debug.Log(c.gameObject.name + "不可视");
                continue;
            }

            Vector2 thisPos   = this.transform.position; //自己的位置
            Vector2 targetPos = c.transform.position;    //检测目标的位置
            Vector2 dir       = this.transform.up;       //自己的方向
            Vector2 targetDir = targetPos - thisPos;     //检测目标的相对位置
            ////坐标cos公式
            //float cos = Vector2.Dot(targetDir, dir) / targetDir.magnitude / dir.magnitude;
            float angle = Vector3.Angle(dir, targetDir) / 180 * Mathf.PI;                   //相对角度角度制

            //Debug.Log(angle);

            float viewAngleRangeArc = ViewAngleRange / 180f * Mathf.PI;                     //探测范围弧度制



            //超出角度判定
            if (angle > viewAngleRangeArc / 2f || angle < -viewAngleRangeArc / 2f)
            {
                //Debug.Log(c.gameObject.name + "超出角度判定");
                continue;
            }


            float checkRange    = Mathf.Asin(sv.VisualRange.radius / targetDir.magnitude) * 2;             //需要检测的角度范围
            int   checkTimes    = (int)(checkRange / (ViewCheckDegrees / 180 * Mathf.PI)) + 1;             //计算检测次数
            float checkRange_r  = ViewCheckOffset * checkRange;                                            //方便边缘检测
            float anglePerCheck = checkRange_r / (checkTimes + 1);                                         //每次增加的角度
            float targetAngle   = Mathf.Atan2(targetDir.y, targetDir.x);                                   //目标方向的绝对角
            float startAngle    = targetAngle - checkRange / 2f + checkRange * (1 - ViewCheckOffset) / 2f; //起始角度
            float currentAngle  = startAngle;                                                              //当前检测的角度

            //检测
            for (int i = 0; i < checkTimes + 2; ++i)
            {
                //射线超出角度剔除
                if (currentAngle - targetAngle > viewAngleRangeArc / 2f || angle < -viewAngleRangeArc / 2f)
                {
                    continue;
                }
                //计算射线的方向向量
                Vector3    v0  = new Vector3(1f, 0f, 0f);
                Quaternion rot = new Quaternion();
                rot.eulerAngles = new Vector3(0, 0, currentAngle / Mathf.PI * 180);
                Vector2 v1 = rot * v0;          //方向向量
                currentAngle += anglePerCheck;  //递增角度

                //进行射线判断
                RaycastHit2D[] hits   = new RaycastHit2D[10];
                int            length = ViewRange.Raycast(v1, vf, hits, ViewRange.radius);
                //什么都没碰到
                if (length <= 0)
                {
                    Debug.DrawLine(thisPos, thisPos + v1 * ViewRange.radius, Color.red);
                    continue;
                }

                //第一个命中
                if (hits[0].collider.gameObject.GetComponent <SensoryVisual>() == sv)
                {
                    memory.UpdateViewRecord(hits[0].collider.gameObject);
                    Debug.DrawLine(thisPos, hits[0].point, Color.green);
                }
                //没命中
                else
                {
                    Debug.DrawLine(thisPos, hits[0].point, Color.red);
                }
            }
        }
    }
    static public Quaternion TrackPointAroundAxis(Vector3 origin, Vector3 target, string rotationAxis, string faceToAlignWithTarget, float factor = 0f)
    {
        Vector3 realitivePosition = (target - origin).normalized;

        float x = 0f, y = 0f, z = 0f, w = 1f;

        float rise = 1f, run = 1f;

        switch (rotationAxis)
        {
        case "y":
        case "Y":
            rise = realitivePosition.x;
            run  = realitivePosition.z;

            switch (faceToAlignWithTarget)
            {
            case "z":
            case "Z":
                y = Mathf.Sin(0.5f * Mathf.Atan2(rise, run));
                w = Mathf.Cos(0.5f * Mathf.Atan2(rise, run));
                break;

            case "-z":
            case "-Z":
                y = Mathf.Cos(0.5f * Mathf.Atan2(rise, run));
                w = -Mathf.Sin(0.5f * Mathf.Atan2(rise, run));
                break;

            case "x":
            case "X":
                y = -Mathf.Sin(0.5f * Mathf.Atan2(run, rise));
                w = Mathf.Cos(0.5f * Mathf.Atan2(run, rise));
                break;

            case "-x":
            case "-X":
                y = Mathf.Cos(0.5f * Mathf.Atan2(run, rise));
                w = Mathf.Sin(0.5f * Mathf.Atan2(run, rise));
                break;

            default:
                break;
            }
            break;

        case "x":
        case "X":
            rise = realitivePosition.y;
            run  = realitivePosition.z;

            switch (faceToAlignWithTarget)
            {
            case "z":
            case "Z":
                x = Mathf.Sin(0.5f * Mathf.Atan2(rise, run));
                w = -Mathf.Cos(0.5f * Mathf.Atan2(rise, run));
                break;

            case "-z":
            case "-Z":

                x = Mathf.Cos(0.5f * Mathf.Atan2(rise, run));
                w = Mathf.Sin(0.5f * Mathf.Atan2(rise, run));

                break;

            case "y":
            case "Y":
                x = Mathf.Sin(0.5f * Mathf.Atan2(run, rise));
                w = Mathf.Cos(0.5f * Mathf.Atan2(run, rise));
                break;

            case "-y":
            case "-Y":
                x = Mathf.Cos(0.5f * Mathf.Atan2(run, rise));
                w = -Mathf.Sin(0.5f * Mathf.Atan2(run, rise));
                break;

            default:
                break;
            }
            break;

        case "z":
        case "Z":
            rise = realitivePosition.x;
            run  = realitivePosition.y;

            switch (faceToAlignWithTarget)
            {
            case "x":
            case "X":
                z = Mathf.Sin(0.5f * Mathf.Atan2(run, rise));
                w = Mathf.Cos(0.5f * Mathf.Atan2(run, rise));
                break;

            case "-x":
            case "-X":
                z = Mathf.Cos(0.5f * Mathf.Atan2(run, rise));
                w = -Mathf.Sin(0.5f * Mathf.Atan2(run, rise));
                break;

            case "y":
            case "Y":
                z = Mathf.Sin(0.5f * Mathf.Atan2(rise, run));
                w = -Mathf.Cos(0.5f * Mathf.Atan2(rise, run));
                break;

            case "-y":
            case "-Y":
                z = Mathf.Cos(0.5f * Mathf.Atan2(rise, run));
                w = Mathf.Sin(0.5f * Mathf.Atan2(rise, run));
                break;

            default:
                break;
            }
            break;

        default:
            break;
        }

        if (factor >= 1f)
        {
            float factorSquared = Mathf.Pow(factor, 2f);

            x = Mathf.Sin((Mathf.Round(Mathf.Asin(x) * (factorSquared / Mathf.PI)) * Mathf.PI) / factorSquared);
            y = Mathf.Sin((Mathf.Round(Mathf.Asin(y) * (factorSquared / Mathf.PI)) * Mathf.PI) / factorSquared);
            z = Mathf.Sin((Mathf.Round(Mathf.Asin(z) * (factorSquared / Mathf.PI)) * Mathf.PI) / factorSquared);
            w = Mathf.Cos((Mathf.Round(Mathf.Acos(w) * (factorSquared / Mathf.PI)) * Mathf.PI) / factorSquared);
        }
        return(new Quaternion(x, y, z, w));
    }
        private static int Helper_PlaceRings(List <GameEntity> entitiesToPlaceWithinZone, ArcenSparseLookup <GameEntity, ArcenPoint> overallEntitySet, bool isQueuedCommand, int paddingAroundEachUnit, ArcenPoint Center, int CurrentOccupiedRadius, NonSimAngleDegrees StartingAngle, NonSimAngleDegrees ArcWidth)
        {
            NonSimAngleRadians arcWidthRadians = ArcWidth.ToRadians();
            int unitIndex = 0;

            while (unitIndex < entitiesToPlaceWithinZone.Count)
            {
                GameEntity firstEntityOnRing = entitiesToPlaceWithinZone[unitIndex];
                int        firstUnitRadius   = firstEntityOnRing.TypeData.Radius + paddingAroundEachUnit;

                int radiusOfNewRing = CurrentOccupiedRadius + firstUnitRadius;

                NonSimAngleRadians workingAngle      = StartingAngle.ToRadians();
                NonSimAngleRadians sumOfArcIncreases = NonSimAngleRadians.Create(0);
                int        lastUnitRadius            = 0;
                ArcenPoint firstPointFound           = ArcenPoint.OutOfRange;
                for ( ; unitIndex < entitiesToPlaceWithinZone.Count; unitIndex++)
                {
                    GameEntity entity = entitiesToPlaceWithinZone[unitIndex];

                    int thisUnitRadius = entity.TypeData.Radius + paddingAroundEachUnit;

                    int distanceNeededFromPreviousPoint = 0;
                    if (lastUnitRadius > 0)
                    {
                        distanceNeededFromPreviousPoint = lastUnitRadius + thisUnitRadius;
                    }
                    lastUnitRadius = thisUnitRadius;

                    if (distanceNeededFromPreviousPoint > 0)
                    {
                        if (distanceNeededFromPreviousPoint > radiusOfNewRing)
                        {
                            break;
                        }
                        if (radiusOfNewRing <= 0)
                        {
                            break;
                        }
                        float unitDistanceNeeded = (float)distanceNeededFromPreviousPoint / (float)radiusOfNewRing; //translating this to "distance" on the unit circle

                        //Given point A at angle M on a circle, increasing the angle by N results in another point at a distance of 2*sin(N/2) from point A
                        //D=2*sin(N/2)
                        //D/2=sin(N/2)
                        //arcsin(D/2)=N/2
                        //2*arcsin(D/2)=N
                        NonSimAngleRadians angleChangeNeeded = NonSimAngleRadians.Create(2 * Mathf.Asin(unitDistanceNeeded / 2));
                        sumOfArcIncreases = sumOfArcIncreases.Add(angleChangeNeeded);
                        if (sumOfArcIncreases.Raw_GetIsGreaterThan(arcWidthRadians))
                        {
                            break; // if this would bring us past the ending angle, stop and go to next "ring" in arc
                        }
                        workingAngle = workingAngle.Add(angleChangeNeeded);
                    }

                    Vector2 pointOnCircle = Center.ToVector2();
                    pointOnCircle.x += (float)(radiusOfNewRing * workingAngle.Cos());
                    pointOnCircle.y += (float)(radiusOfNewRing * workingAngle.Sin());

                    ArcenPoint pointOnCircleAsArcenPoint = pointOnCircle.ToArcenPoint();

                    if (firstPointFound == ArcenPoint.OutOfRange)
                    {
                        firstPointFound = pointOnCircleAsArcenPoint;
                    }
                    else if (firstPointFound.GetDistanceTo(pointOnCircleAsArcenPoint, false) < (firstUnitRadius + thisUnitRadius))
                    {
                        break; // we've come full circle, and don't want to overlap
                    }
                    overallEntitySet[entity] = pointOnCircleAsArcenPoint;
                }

                CurrentOccupiedRadius = radiusOfNewRing + firstUnitRadius;
            }

            return(CurrentOccupiedRadius);
        }
Beispiel #22
0
    static System.Numerics.Vector3 ConvertEuler(UnityEngine.Vector3 r)
    {
        // ZXY Euler to rot matrix

        var x = (r.x > 180.0f ? r.x - 360.0f : r.x) * Mathf.Deg2Rad;
        var y = (r.y > 180.0f ? r.y - 360.0f : r.y) * Mathf.Deg2Rad;
        var z = (r.z > 180.0f ? r.z - 360.0f : r.z) * Mathf.Deg2Rad;

        System.Numerics.Matrix4x4 mat2 = System.Numerics.Matrix4x4.CreateRotationZ(z)
                                         * System.Numerics.Matrix4x4.CreateRotationX(x) * System.Numerics.Matrix4x4.CreateRotationY(y);

        // XYZ
        if (Mathf.Abs(mat2.M13) < 0.99999f)
        {
            y = ((r.y >= 90.0f && r.y < 270.0f) ? Mathf.PI + Mathf.Asin(Mathf.Clamp(mat2.M13, -1.0f, 1.0f)) : -Mathf.Asin(Mathf.Clamp(mat2.M13, -1.0f, 1.0f)));
            x = Mathf.Atan2(mat2.M23 / Mathf.Cos(y), mat2.M33 / Mathf.Cos(y));
            z = Mathf.Atan2(mat2.M12 / Mathf.Cos(y), mat2.M11 / Mathf.Cos(y));
        }
        else
        {
            if (mat2.M31 > 0)
            {
                y = -Mathf.PI / 2.0f;
                x = Mathf.Atan2(-mat2.M21, -mat2.M31);
                z = 0.0f;
            }
            else
            {
                y = Mathf.PI / 2.0f;
                x = Mathf.Atan2(mat2.M21, mat2.M31);
                z = 0.0f;
            }
        }

        return(new System.Numerics.Vector3(Mathf.Rad2Deg * x, Mathf.Rad2Deg * y, Mathf.Rad2Deg * z));
    }
        Vector3 ComputeSunCoords()
        {
            Vector3 result;

            #region Orbital Elements.
            float w = SunOrbitalElements.w; float e = SunOrbitalElements.e; float M = SunOrbitalElements.M;
            float M_Rad = M * Mathf.Deg2Rad;             // M in radians.
            #endregion

            #region Eccentric Anomaly.
            float E     = M + Mathf.Rad2Deg * e * Mathf.Sin(M_Rad) * (1 + e * Mathf.Cos(M_Rad)); //Debug.Log(E);
            float E_Rad = Mathf.Deg2Rad * E;                                                     // E in radians.
            #endregion

            #region Rectangular Coordinates.
            // Rectangular coordinates of the sun in the plane of the ecliptic.
            float xv = (Mathf.Cos(E_Rad) - e);                     //Debug.Log(xv);
            float yv = (Mathf.Sin(E_Rad) * Mathf.Sqrt(1 - e * e)); //Debug.Log(yv);

            // Convert to distance and true anomaly(r = radians, v = degrees).
            float r = Mathf.Sqrt(xv * xv + yv * yv);       //Debug.Log(r);
            float v = Mathf.Rad2Deg * Mathf.Atan2(yv, xv); //Debug.Log(v);

            m_SunDistance = r;                             // Get sun distance.
            #endregion

            #region True Longitude.
            float lonsun = v + w;                      // True sun longitude.
            lonsun = Rev(lonsun);                      //Debug.Log(lonsun) // Solve sun longitude.;

            float lonsun_Rad = Mathf.Deg2Rad * lonsun; // True sun longitude in radians.
            m_TrueSunLongitude = lonsun_Rad;           // Get true sun longitude.
            #endregion

            #region Ecliptic And Equatorial Coordinates.
            // Ecliptic rectangular coordinates(radians):
            float xs = r * Mathf.Cos(lonsun_Rad);
            float ys = r * Mathf.Sin(lonsun_Rad);

            // Ecliptic rectangular coordinates rotate these to equatorial coordinates(radians).
            float oblecl_Cos = Mathf.Cos(Oblecl);
            float oblecl_Sin = Mathf.Sin(Oblecl);

            float xe = xs;
            float ye = ys * oblecl_Cos - 0.0f * oblecl_Sin;
            float ze = ys * oblecl_Sin + 0.0f * oblecl_Cos;
            #endregion

            #region Ascension And Declination.
            float RA   = Mathf.Rad2Deg * Mathf.Atan2(ye, xe) / 15;         // Right ascension(degrees):
            float Decl = Mathf.Atan2(ze, Mathf.Sqrt(xe * xe + ye * ye));   // Declination(radians).
            #endregion

            #region Mean Longitude.
            float L = w + M;          // Mean sun longitude(degrees).
            L = Rev(L);               // Solve mean sun longitude.
            m_MeanSunLongitude = L;   // Get mean sun longitude.
            #endregion

            #region Sideral Time.
            // Sideral time(degrees).
            float GMST0 = (L / 15) + 12;
            m_SideralTime = (GMST0 + HOUR_UTC_APPLY) + (m_Longitude / 15);

            float HA     = (m_SideralTime - RA) * 15;       // Hour angle(degrees).
            float HA_Rad = Mathf.Deg2Rad * HA;              // Hour angle in radians.
            #endregion

            #region Hour Angle And Declination In Rectangular Coordinates.
            // HA anf Decl in rectangular coordinates(radians).
            float Decl_Cos = Mathf.Cos(Decl);

            float x = Mathf.Cos(HA_Rad) * Decl_Cos;             // X axis points to the celestial equator in the south
            float y = Mathf.Sin(HA_Rad) * Decl_Cos;             // Y axis points to the horizon in the west
            float z = Mathf.Sin(Decl);                          // Z axis points to the north celestial pole.

            // Rotate the rectangualar coordinates system along of the Y axis(radians).
            float sinLatitude = Mathf.Sin(Latitude_Rad);
            float cosLatitude = Mathf.Cos(Latitude_Rad);

            float xhor = x * sinLatitude - z * cosLatitude;
            float yhor = y;
            float zhor = x * cosLatitude + z * sinLatitude;
            #endregion

            #region Azimuth, Altitude And Zenith[Radians].
            result.x = Mathf.Atan2(yhor, xhor) + Mathf.PI;
            result.y = Mathf.Asin(zhor);
            result.z = k_HalfPI - result.y;
            #endregion

            return(result);
        }
Beispiel #24
0
        void GeneratedOperationInitializer(OperationType type)
        {
            switch (type)
            {
            case OperationType.Multyply:
                OperationTwoInput    = (a, b) => a * b;
                OperationTwoInputInt = (a, b) => (int)a * b;
                break;

            case OperationType.Divide:
                OperationTwoInput    = (a, b) => a / b;
                OperationTwoInputInt = (a, b) => (int)a / b;
                break;

            case OperationType.Add:
                OperationTwoInput    = (a, b) => a + b;
                OperationTwoInputInt = (a, b) => (int)a + b;
                break;

            case OperationType.Subtract:
                OperationTwoInput    = (a, b) => a - b;
                OperationTwoInputInt = (a, b) => (int)a - b;
                break;

            case OperationType.Negative:
                OperationOneInput    = a => - a;
                OperationOneInputInt = a => (int)-a;
                break;

            case OperationType.Log:
                OperationTwoInput    = Mathf.Log;
                OperationTwoInputInt = (a, b) => (int)Mathf.Log(a, b);
                break;

            case OperationType.Pow:
                OperationTwoInput    = Mathf.Pow;
                OperationTwoInputInt = (a, b) => (int)Mathf.Pow(a, b);
                break;

            case OperationType.Sqrt:
                OperationOneInput    = Mathf.Sqrt;
                OperationOneInputInt = a => (int)Mathf.Sqrt(a);
                break;

            case OperationType.Exp:
                OperationOneInput    = Mathf.Exp;
                OperationOneInputInt = a => (int)Mathf.Exp(a);
                break;

            case OperationType.ClosestPowerOfTwo:
                OperationOneInput    = a => Mathf.ClosestPowerOfTwo((int)a);
                OperationOneInputInt = a => (int)Mathf.ClosestPowerOfTwo((int)a);
                break;

            case OperationType.PerlinNoise:
                OperationTwoInput    = Mathf.PerlinNoise;
                OperationTwoInputInt = (a, b) => (int)Mathf.PerlinNoise(a, b);
                break;

            case OperationType.Repeat:
                OperationTwoInput    = Mathf.Repeat;
                OperationTwoInputInt = (a, b) => (int)Mathf.Repeat(a, b);
                break;

            case OperationType.PingPong:
                OperationTwoInput    = Mathf.PingPong;
                OperationTwoInputInt = (a, b) => (int)Mathf.PingPong(a, b);
                break;

            case OperationType.Abs:
                OperationOneInput    = Mathf.Abs;
                OperationOneInputInt = a => (int)Mathf.Abs(a);
                break;

            case OperationType.Sign:
                OperationOneInput    = Mathf.Sign;
                OperationOneInputInt = a => (int)Mathf.Sign(a);
                break;

            case OperationType.Round:
                OperationOneInput    = Mathf.Round;
                OperationOneInputInt = a => (int)Mathf.Round(a);
                break;

            case OperationType.Floor:
                OperationOneInput    = Mathf.Floor;
                OperationOneInputInt = a => (int)Mathf.Floor(a);
                break;

            case OperationType.Ceil:
                OperationOneInput    = Mathf.Ceil;
                OperationOneInputInt = a => (int)Mathf.Ceil(a);
                break;

            case OperationType.Max:
                OperationTwoInput    = Mathf.Max;
                OperationTwoInputInt = (a, b) => (int)Mathf.Max(a, b);
                break;

            case OperationType.Min:
                OperationTwoInput    = Mathf.Min;
                OperationTwoInputInt = (a, b) => (int)Mathf.Min(a, b);
                break;

            case OperationType.Clamp01:
                OperationOneInput    = Mathf.Clamp01;
                OperationOneInputInt = a => (int)Mathf.Clamp01(a);
                break;

            case OperationType.Sin:
                OperationOneInput    = Mathf.Sin;
                OperationOneInputInt = a => (int)Mathf.Sin(a);
                break;

            case OperationType.Cos:
                OperationOneInput    = Mathf.Cos;
                OperationOneInputInt = a => (int)Mathf.Cos(a);
                break;

            case OperationType.Tan:
                OperationOneInput    = Mathf.Tan;
                OperationOneInputInt = a => (int)Mathf.Tan(a);
                break;

            case OperationType.Asin:
                OperationOneInput    = Mathf.Asin;
                OperationOneInputInt = a => (int)Mathf.Asin(a);
                break;

            case OperationType.Acos:
                OperationOneInput    = Mathf.Acos;
                OperationOneInputInt = a => (int)Mathf.Acos(a);
                break;

            case OperationType.Atan:
                OperationOneInput    = Mathf.Atan;
                OperationOneInputInt = a => (int)Mathf.Atan(a);
                break;

            case OperationType.Atan2:
                OperationTwoInput    = Mathf.Atan2;
                OperationTwoInputInt = (a, b) => (int)Mathf.Atan2(a, b);
                break;
            }
        }
Beispiel #25
0
        public void FixedUpdate() // FixedUpdate is also called when not activated
        {
            currentRadiatorArea = RadiatorArea;

            if (!HighLogic.LoadedSceneIsFlight)
            {
                return;
            }

            if (vessel.altitude <= PluginHelper.getMaxAtmosphericAltitude(vessel.mainBody))
            {
                float pressure         = ((float)FlightGlobals.getStaticPressure(vessel.transform.position) / 100f);
                float dynamic_pressure = (float)(0.5f * pressure * 1.2041f * vessel.srf_velocity.sqrMagnitude / 101325.0f);
                pressure += dynamic_pressure;
                float low_temp = (float)FlightGlobals.getExternalTemperature(vessel.transform.position);

                float  delta_temp        = Mathf.Max(0, (float)current_rad_temp - low_temp);
                double conv_power_dissip = pressure * delta_temp * RadiatorArea * rad_const_h / 1e6f * TimeWarp.fixedDeltaTime * convectiveBonus;
                if (!radiatorIsEnabled)
                {
                    conv_power_dissip = conv_power_dissip / 2.0f;
                }

                convectedThermalPower = consumeWasteHeat(conv_power_dissip);

                if (isDeployable)
                {
                    DeployMentControl(dynamic_pressure);
                }
            }
            else
            {
                pressureLoad = 0;
                if (!radiatorIsEnabled && isAutomated)
                {
                    Deploy();
                }
            }

            wasteheatRatio = (float)getResourceBarRatio(FNResourceManager.FNRESOURCE_WASTEHEAT);

            radiator_temperature_temp_val = RadiatorTemperature * Mathf.Pow(wasteheatRatio, 0.25f);

            var activeThermalSources = GetActiveThermalSources();

            if (activeThermalSources.Any())
            {
                radiator_temperature_temp_val = Math.Min(Mathf.Min(GetAverageTemperatureofOfThermalSource(activeThermalSources)) / 1.01f, radiator_temperature_temp_val);
            }

            if (radiatorIsEnabled)
            {
                if (wasteheatRatio >= 1 && current_rad_temp >= RadiatorTemperature)
                {
                    explode_counter++;
                    if (explode_counter > 25)
                    {
                        part.explode();
                    }
                }
                else
                {
                    explode_counter = 0;
                }

                float fixed_thermal_power_dissip = Mathf.Pow(radiator_temperature_temp_val, 4) * GameConstants.stefan_const * RadiatorArea / 1e6f * TimeWarp.fixedDeltaTime;

                if (Single.IsNaN(fixed_thermal_power_dissip))
                {
                    Debug.LogWarning("FNRadiator: OnFixedUpdate Single.IsNaN detected in fixed_thermal_power_dissip");
                }

                radiatedThermalPower = consumeWasteHeat(fixed_thermal_power_dissip);

                if (Single.IsNaN(radiatedThermalPower))
                {
                    Debug.LogError("FNRadiator: OnFixedUpdate Single.IsNaN detected in radiatedThermalPower after call consumeWasteHeat (" + fixed_thermal_power_dissip + ")");
                }

                instantaneous_rad_temp = Mathf.Min(radiator_temperature_temp_val * 1.014f, RadiatorTemperature);
                instantaneous_rad_temp = Mathf.Max(instantaneous_rad_temp, Mathf.Max((float)FlightGlobals.getExternalTemperature(vessel.altitude, vessel.mainBody), 2.7f));

                if (Single.IsNaN(instantaneous_rad_temp))
                {
                    Debug.LogError("FNRadiator: OnFixedUpdate Single.IsNaN detected in instantaneous_rad_temp after reading external temperature");
                }

                current_rad_temp = instantaneous_rad_temp;

                if (isDeployable)
                {
                    pivot.Rotate(Vector3.up * 5f * TimeWarp.fixedDeltaTime * directionrotate);

                    Vector3 sunpos             = FlightGlobals.Bodies [0].transform.position;
                    Vector3 flatVectorToTarget = sunpos - transform.position;

                    flatVectorToTarget = flatVectorToTarget.normalized;
                    float dot = Mathf.Asin(Vector3.Dot(pivot.transform.right, flatVectorToTarget)) / Mathf.PI * 180.0f;

                    float anglediff = -dot;
                    directionrotate = anglediff / 5 / TimeWarp.fixedDeltaTime;
                    directionrotate = Mathf.Min(3, directionrotate);
                    directionrotate = Mathf.Max(-3, directionrotate);

                    part.maximum_drag = 0.8f;
                    part.minimum_drag = 0.8f;
                }
            }
            else
            {
                if (isDeployable)
                {
                    pivot.transform.localEulerAngles = original_eulers;
                }

                float fixed_thermal_power_dissip = Mathf.Pow(radiator_temperature_temp_val, 4) * GameConstants.stefan_const * RadiatorArea / 0.5e7f * TimeWarp.fixedDeltaTime;

                radiatedThermalPower = consumeWasteHeat(fixed_thermal_power_dissip);

                instantaneous_rad_temp = Mathf.Min(radiator_temperature_temp_val * 1.014f, RadiatorTemperature);
                instantaneous_rad_temp = Mathf.Max(instantaneous_rad_temp, Mathf.Max((float)FlightGlobals.getExternalTemperature((float)vessel.altitude, vessel.mainBody), 2.7f));

                current_rad_temp = instantaneous_rad_temp;

                part.maximum_drag = 0.2f;
                part.minimum_drag = 0.2f;
            }
        }
    void Update()
    {
        if (data_right != null)
        {
            ////RotateFromQ(trans_right[0], data_right.Joints[0].ToQuaternion());
            //var qq = data_right.Joints[0].ToQuaternion();
            //var euler1 = new Vector3();
            //euler1.z = Mathf.Atan2(2 * (qq.w * qq.z + qq.x * qq.y), 1 - 2 * (qq.z * qq.z + qq.x * qq.x));
            //euler1.x = Mathf.Asin(2 * (qq.w * qq.x - qq.z * qq.y));
            //euler1.y = Mathf.Atan2(2 * (qq.w * qq.y + qq.x * qq.z), 1 - 2 * (qq.x * qq.x + qq.y * qq.y));
            //euler1 = euler1 * Mathf.Rad2Deg;


            //var qqea = qq.eulerAngles;
            //var qqq = Quaternion.Euler(qqea.x, -qqea.y, -qqea.z);
            //RotateFromQ(trans_right[0], qqq);


            ////Debug.Log("this is my euler" + euler1 + "this is unity euler" + qqea);

            //for (int i = 1; i < 2; i++)
            //{
            //    int index = 1;
            //    //near joint
            //    var q = data_right.Joints[index + 1].ToQuaternion();
            //    var ea = q.eulerAngles;
            //    //bend angle
            //    var bend = ea.z;
            //    if (modelType == ModelType.HandOnly)
            //    {
            //        //new model
            //        bend = RestrictAngle(bend, -98, 10);
            //    }
            //    else
            //    {
            //        //old model
            //        bend = RestrictAngle(bend, -10, 90);
            //    }
            //    //strech angle
            //    var strech = ea.y;

            //    strech = RestrictAngle(strech, -30, 10);

            //    if (bend > -30)
            //    {
            //        strech = strech;
            //    }
            //    else if (bend < -50)
            //    {
            //        strech = 0;
            //    }
            //    else
            //    {
            //        strech *= (bend + 50) / 20.0f;
            //    }
            //    q = Quaternion.AngleAxis(strech, new Vector3(0, 1, 0));
            //    q *= Quaternion.AngleAxis(bend, new Vector3(0, 0, 1));
            //    RotateFromQ(trans_right[index], q);//near

            //    //middle joint
            //    q = data_right.Joints[index + 2].ToQuaternion();
            //    if (i == 1)
            //    {
            //        //Debug.Log (q.eulerAngles);
            //    }
            //    float bend1 = 0;
            //    if (modelType == ModelType.HandOnly)
            //    {
            //        //new model
            //        bend1 = RestrictAngle(q.eulerAngles.z, -90, 0);
            //    }
            //    else
            //    {
            //        //old model
            //        bend1 = RestrictAngle(q.eulerAngles.z, 0, 90);
            //    }
            //    q = Quaternion.AngleAxis(bend1, new Vector3(0, 0, 1));
            //    RotateFromQ(trans_right[index + 1], q);

            //    //far joint
            //    q = data_right.Joints[index + 2].ToQuaternion();
            //    float bend2 = 0;
            //    //double hand
            //    if (modelType == ModelType.HandOnly)
            //    {
            //        //new model
            //        bend2 = RestrictAngle(q.eulerAngles.z, -90, 0);
            //    }
            //    else
            //    {
            //        //old model
            //        bend2 = RestrictAngle(q.eulerAngles.z, 0, 90);
            //    }
            //    //old model
            //    q = Quaternion.AngleAxis(bend2, new Vector3(0, 0, 1));
            //    RotateFromQ(trans_right[index + 2], q);

            //}

            //for (int i = 4; i < 7; i++)
            //{
            //    RotateFromQ(trans_right[i], data_right.Joints[i].ToQuaternion());
            //}

            //for (int i = 1; i < 4; i++)
            //{
            //    int index = i * 3 + 4;
            //    //near joint
            //    var q = data_right.Joints[index].ToQuaternion();
            //    var ea = q.eulerAngles;
            //    //bend angle
            //    var bend = ea.z;
            //    if (modelType == ModelType.HandOnly)
            //    {
            //        //new model
            //        bend = RestrictAngle(bend, -98, 10);
            //    }
            //    else
            //    {
            //        //old model
            //        bend = RestrictAngle(bend, -10, 90);
            //    }
            //    //strech angle
            //    var strech = ea.y;
            //    if (i == 1)
            //    {//index finger
            //        strech = RestrictAngle(strech, -10, 30);
            //    }
            //    else if (i == 2)
            //    { //middle finger
            //        strech = RestrictAngle(strech, -10, 10);
            //    }
            //    else
            //    {//ring and little
            //        strech = RestrictAngle(strech, -30, 10);
            //    }
            //    if (bend > -30)
            //    {
            //        strech = strech;
            //    }
            //    else if (bend < -50)
            //    {
            //        strech = 0;
            //    }
            //    else
            //    {
            //        strech *= (bend + 50) / 20.0f;
            //    }
            //    q = Quaternion.AngleAxis(strech, new Vector3(0, 1, 0));
            //    q *= Quaternion.AngleAxis(bend, new Vector3(0, 0, 1));
            //    RotateFromQ(trans_right[index], q);//near

            //    //middle joint
            //    q = data_right.Joints[index + 1].ToQuaternion();
            //    if (i == 1)
            //    {
            //        //Debug.Log (q.eulerAngles);
            //    }
            //    float bend1 = 0;
            //    if (modelType == ModelType.HandOnly)
            //    {
            //        //new model
            //        bend1 = RestrictAngle(q.eulerAngles.z, -90, 0);
            //    }
            //    else
            //    {
            //        //old model
            //        bend1 = RestrictAngle(q.eulerAngles.z, 0, 90);
            //    }
            //    q = Quaternion.AngleAxis(bend1, new Vector3(0, 0, 1));
            //    RotateFromQ(trans_right[index + 1], q);

            //    //far joint
            //    q = data_right.Joints[index + 2].ToQuaternion();
            //    float bend2 = 0;
            //    //double hand
            //    if (modelType == ModelType.HandOnly)
            //    {
            //        //new model
            //        bend2 = RestrictAngle(q.eulerAngles.z, -90, 0);
            //    }
            //    else
            //    {
            //        //old model
            //        bend2 = RestrictAngle(q.eulerAngles.z, 0, 90);
            //    }
            //    //old model
            //    q = Quaternion.AngleAxis(bend2, new Vector3(0, 0, 1));
            //    RotateFromQ(trans_right[index + 2], q);
            //}
            ////right  arm
            //RotateFromQ(trans_right[16], data_right.Joints[16].ToQuaternion());
            //RotateFromQ(trans_right[17], data_right.Joints[17].ToQuaternion());
            //RotateFromQ(trans_right[18], data_right.Joints[18].ToQuaternion());


            //RotateFromQ(trans_right[0], data_right.Joints[0].ToQuaternion());
            var qq = data_right.Joints[0].ToQuaternion();
            //Debug.Log("qq.x: " + qq.x + "qqq1.y:" + qq.y + "qq.z:" + qq.z + "qq.w:" + qq.w);
            var euler1 = new Vector3();
            euler1.z = Mathf.Atan2(2 * (qq.w * qq.z + qq.x * qq.y), 1 - 2 * (qq.z * qq.z + qq.x * qq.x));
            euler1.x = Mathf.Asin(2 * (qq.w * qq.x - qq.z * qq.y));
            euler1.y = Mathf.Atan2(2 * (qq.w * qq.y + qq.x * qq.z), 1 - 2 * (qq.x * qq.x + qq.y * qq.y));
            euler1   = euler1 * Mathf.Rad2Deg;


            var qqea = qq.eulerAngles;
            var qqq  = Quaternion.Euler(qqea.x, -qqea.y, -qqea.z);
            RotateFromQ(trans_right[0], qqq);

            //Debug.Log("qqq is: " + qqq);
            //Debug.Log("this is my euler" + euler1 + "this is unity euler" + qqea);

            for (int i = 1; i < 2; i++)
            {
                int index = 1;
                //near joint
                var q  = data_right.Joints[index + 1].ToQuaternion();
                var ea = q.eulerAngles;
                //bend angle
                var bend = ea.z;

                bend = RestrictAngle(bend, -98, 10);


                //strech angle
                var strech = ea.y - 180;

                strech = RestrictAngle(strech, -10, 30);

                if (bend > -30)
                {
                    strech = strech;
                }
                else if (bend < -50)
                {
                    strech = 0;
                }
                else
                {
                    strech *= (bend + 50) / 20.0f;
                }
                q  = Quaternion.AngleAxis(-strech, new Vector3(0, 1, 0));
                q *= Quaternion.AngleAxis(bend, new Vector3(0, 0, 1));
                RotateFromQ(trans_right[index], q);//near

                //middle joint
                q = data_right.Joints[index + 2].ToQuaternion();
                float bend1 = 0;
                bend1 = RestrictAngle(q.eulerAngles.z, 0, 90);
                q     = Quaternion.AngleAxis(-bend1, new Vector3(0, 0, 1));
                RotateFromQ(trans_right[index + 1], q);

                //far joint
                q = data_right.Joints[index + 2].ToQuaternion();
                float bend2 = 0;
                bend2 = RestrictAngle(q.eulerAngles.z, 0, 90);
                q     = Quaternion.AngleAxis(-bend2, new Vector3(0, 0, 1));
                RotateFromQ(trans_right[index + 2], q);
            }

            //RotateFromQ(trans_right[4], data_right.Joints[13].ToQuaternion());


            var qqqea = data_right.Joints[13].ToQuaternion().eulerAngles;
            var qqqq  = Quaternion.Euler(qqqea.x, -qqqea.y + 15, -qqqea.z);
            var qy    = Quaternion.Euler(0, 180, 0);
            RotateFromQ(trans_right[4], qqqq * qy);
            //Debug.Log("thumb euler is: " + qqqea);

            for (int i = 5; i < 7; i++)
            {
                //RotateFromQ(trans_right[i], data_right.Joints[9 + i].ToQuaternion());
                var   q     = data_right.Joints[14].ToQuaternion();
                float bend1 = 0;
                bend1 = RestrictAngle(q.eulerAngles.z, 0, 90);
                q     = Quaternion.AngleAxis(-bend1, new Vector3(0, 0, 1));
                RotateFromQ(trans_right[i], q);
            }

            for (int i = 1; i < 4; i++)
            {
                int index = i * 3 + 4;
                //near joint
                var q  = data_right.Joints[13 - 3 * i].ToQuaternion();
                var ea = q.eulerAngles;
                //bend angle
                var bend = ea.z;

                bend = RestrictAngle(bend, -98, 10);

                //strech angle
                var strech = ea.y - 180;
                if (i == 1)
                {//index finger
                    strech = RestrictAngle(strech, -30, 10);
                }
                else if (i == 2)
                { //middle finger
                    strech = RestrictAngle(strech, -10, 10);
                }
                else
                {//ring and little
                    strech = RestrictAngle(strech, -10, 20);
                }
                if (bend > -30)
                {
                    strech = strech;
                }
                else if (bend < -50)
                {
                    strech = 0;
                }
                else
                {
                    strech *= (bend + 50) / 20.0f;
                }
                q  = Quaternion.AngleAxis(-strech, new Vector3(0, 1, 0));
                q *= Quaternion.AngleAxis(bend, new Vector3(0, 0, 1));
                RotateFromQ(trans_right[index], q);//near

                //middle joint
                q = data_right.Joints[14 - 3 * i].ToQuaternion();
                float bend1 = 0;
                bend1 = RestrictAngle(q.eulerAngles.z, 0, 90);
                q     = Quaternion.AngleAxis(-bend1, new Vector3(0, 0, 1));
                RotateFromQ(trans_right[index + 1], q);
                RotateFromQ(trans_right[index + 2], q);
            }
            //right  arm
            RotateFromQ(trans_right[16], data_right.Joints[16].ToQuaternion());
            RotateFromQ(trans_right[17], data_right.Joints[17].ToQuaternion());
            RotateFromQ(trans_right[18], data_right.Joints[18].ToQuaternion());
        }

        //left
        if (data_left != null)
        {
            for (int i = 0; i < 4; i++)
            {
                RotateFromQ(trans_left[i], data_left.Joints[i].ToQuaternion());
            }
            for (int i = 0; i < 4; i++)
            {
                int index = i * 3 + 4;
                //near joint
                var q  = data_left.Joints[index].ToQuaternion();
                var ea = q.eulerAngles;
                //bend angle
                var bend = ea.z;
                bend = RestrictAngle(bend, -98, 10);
                //strech angle
                var strech = ea.y;
                if (i == 0)
                {//index finger
                    strech = RestrictAngle(strech, -10, 30);
                }
                else if (i == 1)
                { //middle finger
                    strech = RestrictAngle(strech, -10, 10);
                }
                else
                {//ring and little
                    strech = RestrictAngle(strech, -30, 10);
                }
                if (bend > -30)
                {
                    strech = strech;
                }
                else if (bend < -50)
                {
                    strech = 0;
                }
                else
                {
                    strech *= (bend + 50) / 20.0f;
                }
                q  = Quaternion.AngleAxis(strech, new Vector3(0, 1, 0));
                q *= Quaternion.AngleAxis(bend, new Vector3(0, 0, 1));
                RotateFromQ(trans_left[index], q);//near

                //middle joint
                q = data_left.Joints[index + 1].ToQuaternion();
                var bend1 = RestrictAngle(q.eulerAngles.z, -94, 0);
                q = Quaternion.AngleAxis(bend1, new Vector3(0, 0, 1));
                RotateFromQ(trans_left[index + 1], q);
                //far joint
                q = data_left.Joints[index + 2].ToQuaternion();
                var bend2 = RestrictAngle(q.eulerAngles.z, -94, 0);
                q = Quaternion.AngleAxis(bend2, new Vector3(0, 0, 1));
                RotateFromQ(trans_left[index + 2], q);
            }
            //left fore arm
            //RotateFromQ(trans_left[16], data_left.Joints[16].ToQuaternion());
        }
    }
Beispiel #27
0
 static float SafeAsin(float y, float r)
 {
     return(r <= 0 ? 0 : Mathf.Asin(y / r));
 }
        public Matrix <float> inv_kin(Matrix <float> pose)
        {
            // pose is the 4x4 matrix of the end effector

            Matrix <float> theta = Matrix <float> .Build.Dense(6, 8);

            // theta1
            var temp1 = Vector <float> .Build.DenseOfArray(new float[] { 0, 0, -d[5], 1 });

            var temp2 = Vector <float> .Build.DenseOfArray(new float[] { 0, 0, 0, 1 });

            var p05 = (pose * temp1) - temp2;
            var psi = Mathf.Atan2(p05[1], p05[0]);
            var phi = 0f;

            if (d[3] / Mathf.Sqrt(p05[1] * p05[1] + p05[0] * p05[0]) > 1)
            {
                phi = 0f;
            }
            else
            {
                phi = Mathf.Acos(d[3] / Mathf.Sqrt(p05[1] * p05[1] + p05[0] * p05[0]));
            }
            //theta[0, :4] = m.pi / 2 + psi + phi;
            theta.SetSubMatrix(0, 0, Matrix <float> .Build.Dense(1, 4, Mathf.PI / 2 + psi + phi));
            //theta[0, 4:8] = Mathf.PI / 2 + psi - phi;
            theta.SetSubMatrix(0, 4, Matrix <float> .Build.Dense(1, 4, Mathf.PI / 2 + psi - phi));

            // theta5
            for (int c = 0; c < 4; c++)
            {
                var T10  = DH(a[0], alpha[0], d[0], theta[0, c]).Inverse();
                var T16  = (T10 * pose);
                var p16z = T16[2, 3];
                var t5   = 0f;
                if ((p16z - d[3]) / d[5] > 1)
                {
                    t5 = 0f;
                }
                else
                {
                    t5 = Mathf.Acos((p16z - d[3]) / d[5]);
                }

                //theta[4, c: c + 1 + 1] = t5;
                //theta[4, c + 2:c + 3 + 1] = -t5;
                theta[4, c]     = t5;
                theta[4, c + 1] = t5;
                theta[4, c + 2] = -t5;
                theta[4, c + 3] = -t5;
            }

            // theta6
            for (int c = 0; c <= 6 && c % 2 == 0; c++)
            {
                var T01   = DH(a[0], alpha[0], d[0], theta[0, c]);
                var T61   = pose.Inverse() * T01;
                var T61zy = T61[1, 2];
                var T61zx = T61[0, 2];
                var t5    = theta[4, c];
                //theta[5, c: c + 1 + 1] = Mathf.Atan2(-T61zy / Mathf.Sin(t5), T61zx / Mathf.Sin(t5));
                theta[5, c]     = Mathf.Atan2(-T61zy / Mathf.Sin(t5), T61zx / Mathf.Sin(t5));
                theta[5, c + 1] = Mathf.Atan2(-T61zy / Mathf.Sin(t5), T61zx / Mathf.Sin(t5));
            }

            // theta3
            for (int c = 0; c <= 6 && c % 2 == 0; c++)
            {
                var T10 = DH(a[0], alpha[0], d[0], theta[0, c]).Inverse();
                var T65 = DH(a[5], alpha[5], d[5], theta[5, c]).Inverse();
                var T54 = DH(a[4], alpha[4], d[4], theta[4, c]).Inverse();
                var T14 = ((T10 * pose) * (T65 * T54));
                temp1 = Vector <float> .Build.DenseOfArray(new float[] { 0, -d[3], 0, 1 });

                temp2 = Vector <float> .Build.DenseOfArray(new float[] { 0, 0, 0, 1 });

                var p13 = (T14 * temp1) - temp2;
                //var p13norm2 = la.norm(p13) * *2;  // Frobenius norm
                var p13norm2 = p13.Norm(2) * p13.Norm(2);  // L2 norm is same?
                var t3p      = 0f;
                if ((p13norm2 - a[1] * a[1] - a[2] * a[2]) / (2 * a[1] * a[2]) > 1)
                {
                    t3p = 0f;
                }
                else
                {
                    t3p = Mathf.Acos(((float)p13norm2 - a[1] * a[1] - a[2] * a[2]) / (2 * a[1] * a[2]));
                }
                theta[2, c]     = t3p;
                theta[2, c + 1] = -t3p;
            }

            // theta2 theta4
            for (int c = 0; c < 8; c++)
            {
                var T10 = DH(a[0], alpha[0], d[0], theta[0, c]).Inverse();
                var T65 = DH(a[5], alpha[5], d[5], theta[5, c]).Inverse();
                var T54 = DH(a[4], alpha[4], d[4], theta[4, c]).Inverse();
                var T14 = ((T10 * pose) * (T65 * T54));
                temp1 = Vector <float> .Build.DenseOfArray(new float[] { 0, -d[3], 0, 1 });

                temp2 = Vector <float> .Build.DenseOfArray(new float[] { 0, 0, 0, 1 });

                var p13     = (T14 * temp1) - temp2;
                var p13norm = p13.Norm(2);
                theta[1, c] = -Mathf.Atan2(p13[1], -p13[0]) + Mathf.Asin(a[2] * Mathf.Sin(theta[2, c]) / (float)p13norm);
                var T32 = DH(a[2], alpha[2], d[2], theta[2, c]).Inverse();
                var T21 = DH(a[1], alpha[1], d[1], theta[1, c]).Inverse();
                var T34 = ((T32 * T21) * T14);
                theta[3, c] = Mathf.Atan2(T34[1, 0], T34[0, 0]);
            }

            for (int i = 0; i < theta.RowCount; i++)
            {
                for (int j = 0; j < theta.ColumnCount; j++)
                {
                    if (theta[i, j] > Mathf.PI)
                    {
                        theta[i, j] = theta[i, j] - 2 * Mathf.PI;
                    }
                    if (theta[i, j] < -1 * Mathf.PI)
                    {
                        theta[i, j] = theta[i, j] + 2 * Mathf.PI;
                    }
                }
            }

            return(theta);
        }
Beispiel #29
0
 protected float asin(float x)
 {
     return(Mathf.Asin(x));
 }
Beispiel #30
0
    private void updateCannonRotation()
    {
        if (!IsLeftCannonReady)
        {
            // rotate the cannon, its no longer in player control
            if (LeftCannonCrosshair != null)
            {
                // if crosshair is not null then that means the missile is not fired yet
                lc_TimeElapsedRotating += Time.deltaTime;
                Quaternion tmp = Quaternion.Lerp(lc_StartRotation, lc_EndRotation, lc_TimeElapsedRotating / lc_TotalTimeRotating);

                LeftCannon.transform.localRotation = tmp;

                if (lc_TimeElapsedRotating >= lc_TotalTimeRotating)
                {
                    Vector3 relativePos = LeftCannonCrosshair.transform.position - LeftCannon.transform.position;
                    float   distance    = Vector3.Distance(Vector3.zero, relativePos);
                    float   angle       = Mathf.Asin(relativePos.x / distance) * Mathf.Rad2Deg;

                    Vector3 pos = LeftCannon.transform.position + LeftCannon.transform.up * 0.5f;
                    pos.z += 0.3f;

                    GameObject  obj     = GameNetworkManager.singleton.SpawnNetworkAwareObject(flakMissile.gameObject, pos, Quaternion.Euler(0, 0, -angle));
                    FlakMissile missile = obj.GetComponent <FlakMissile>();
                    missile.FollowObject = LeftCannonCrosshair;

                    LeftCannonCrosshair = null;
                    lc_TimeElapsed      = 0.0f;
                }
            }
            else
            {
                lc_TimeElapsed += Time.deltaTime;

                if (lc_TimeElapsed >= LeftCannonCooldown)
                {
                    IsLeftCannonReady = true;
                }
            }
        }

        if (!IsRightCannonReady)
        {
            // rotate the cannon, its no longer in player control
            if (RightCannonCrosshair != null)
            {
                // if crosshair is not null then that means the missile is not fired yet

                rc_TimeElapsedRotating += Time.deltaTime;
                Quaternion tmp = Quaternion.Lerp(rc_StartRotation, rc_EndRotation, rc_TimeElapsedRotating / rc_TotalTimeRotating);

                RightCannon.transform.localRotation = tmp;

                if (rc_TimeElapsedRotating >= rc_TotalTimeRotating)
                {
                    Vector3 relativePos = RightCannonCrosshair.transform.position - RightCannon.transform.position;
                    float   distance    = Vector3.Distance(Vector3.zero, relativePos);
                    float   angle       = Mathf.Asin(relativePos.x / distance) * Mathf.Rad2Deg;

                    Vector3 pos = RightCannon.transform.position + RightCannon.transform.up * 0.5f;
                    pos.z += 0.3f;

                    GameObject  obj     = GameNetworkManager.singleton.SpawnNetworkAwareObject(flakMissile.gameObject, pos, Quaternion.Euler(0, 0, 180.0f + angle));
                    FlakMissile missile = obj.GetComponent <FlakMissile>();
                    missile.FollowObject = RightCannonCrosshair;

                    RightCannonCrosshair = null;
                    rc_TimeElapsed       = 0.0f;
                }
            }
            else
            {
                rc_TimeElapsed += Time.deltaTime;

                if (rc_TimeElapsed >= RightCannonCooldown)
                {
                    IsRightCannonReady = true;
                }
            }
        }
    }