Esempio n. 1
0
    // Update is called once per frame
    void Update()
    {
        if (TimeCount.gameOver)
        {
            return;
        }
        if (colorUsed[selectColorindex] == 0)
        {
            return;
        }
        bool Mousedown = Input.GetMouseButton(0);

        if (Input.GetMouseButtonDown(0) && !isclicked && rolecontroller.isrunning)
        {
            if (UICamera.hoveredObject != null)
            {
                if (UICamera.hoveredObject.tag.Equals("SelectColor") ||
                    UICamera.hoveredObject.tag.Equals("stopButton"))
                {
                    return;
                }
            }
            singleUsed     = 0;
            Time.timeScale = 0.2f;
            beginposition  = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
                                                                        Input.mousePosition.y, 1));
            print(beginposition.ToString());
            isclicked = true;
            tr        = (Transform)Instantiate(prefab, new Vector3(beginposition.x, beginposition.y, 0),
                                               Quaternion.identity);
            tr.parent = parent;

            lineRender = tr.GetComponent <LineRenderer>();
            lineRender.material.color = linecolor[selectColorindex];
            lineRender.SetWidth(0.5f, 0.5f);
            lineRender.SetVertexCount(3);
            lineRender.SetPosition(0, new Vector3(beginposition.x, beginposition.y, -0.5f));
        }
        if (Mousedown && isclicked && rolecontroller.isrunning)
        {
            midposition = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
                                                                     Input.mousePosition.y, 1));
            //  lineRender.SetPosition(1, midposition);
            //  lineRender.SetPosition(2, beginposition);
            lineRender.SetPosition(1, new Vector3(midposition.x, midposition.y, -0.5f));
            lineRender.SetPosition(2, new Vector3(beginposition.x, beginposition.y, -0.5f));
            singleUsed = InvSqrt(midposition.x, beginposition.x, midposition.y, beginposition.y);
        }

        if (Input.GetMouseButtonUp(0) && isclicked && rolecontroller.isrunning)
        {
            isclicked      = false;
            Mousedown      = false;
            Time.timeScale = 1.0f;
            endposition    = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
                                                                        Input.mousePosition.y, 1));
            float     angle    = Mathf.Atan2((beginposition.y - endposition.y), (beginposition.x - endposition.x));
            float     distance = Mathf.Sqrt(Mathf.Pow((beginposition.y - endposition.y), 2) + Mathf.Pow((beginposition.x - endposition.x), 2));
            Transform tr1      = (Transform)Instantiate(prefab1, (beginposition + endposition) / 2, Quaternion.AngleAxis(angle * 180 / 3.14f, Vector3.forward));
            boxcollider2D                = tr1.GetComponent <BoxCollider2D>();
            boxcollider2D.size           = new Vector2(distance, 0.2f);
            colorUsed[selectColorindex] -= singleUsed;
            if (colorUsed[selectColorindex] <= 0)
            {
                colorUsed[selectColorindex] = 0;
            }
            sendmsg[selectColorindex].SendMessage("ColorChangetoMuch", colorUsed[selectColorindex]);
        }
    }
    public void UpdateNet()
    {
        float angle       = -90;
        float angleAdd    = 22.5f;
        float distance    = 3f;
        float outDistance = 0.35f;

        Vector3[]      direction        = new Vector3[numberOfSensors];
        Vector3[]      relativePosition = new Vector3[numberOfSensors];
        RaycastHit2D[] rayHit           = new RaycastHit2D[numberOfSensors];

        float redness   = 1f - (damage / 100f);
        Color lineColor = new Color(1f, redness, redness);

        for (int i = 0; i < numberOfSensors; i++)
        {
            direction[i]        = Quaternion.AngleAxis(angle, Vector3.forward) * transform.up;
            relativePosition[i] = transform.position + (outDistance * direction[i]);
            rayHit[i]           = Physics2D.Raycast(relativePosition[i], direction[i], distance);
            lines[i].SetPosition(0, relativePosition[i]);
            sightHit[i] = -1f;

            if (rayHit[i].collider != null)
            {
                sightHit[i] = Vector2.Distance(rayHit[i].point, transform.position) / (distance);
                lines[i].SetPosition(1, rayHit[i].point);
            }
            else
            {
                lines[i].SetPosition(1, relativePosition[i]);
            }

            lines[i].SetColors(lineColor, lineColor);

            angle += angleAdd;
        }

        int num = Physics2D.OverlapCircleAll(transform.position, 0.3f).Length;

        num--;

        float[] inputValues =
        {
            sightHit[0],   sightHit[1],  sightHit[2],
            sightHit[3],   sightHit[4],  sightHit[5],
            sightHit[6],   sightHit[7],  sightHit[8],
            sightHit[9],   sightHit[10], sightHit[11],
            damage / 100f, num
        };

        float[] output = net.FireNet(inputValues);

        if (output[0] > 0)
        {
            rBody.velocity = 7 * transform.up * output[0];
        }
        else
        {
            rBody.velocity = rBody.velocity.magnitude * transform.up;
        }
        rBody.angularVelocity = 200f * output[1];

        float turn = (1f - Mathf.Abs(output[1]) / 100f);
        //net.AddNetFitness(turn/2f);
    }
    Quaternion RotationForIndex(int curIndex)
    {
        float angle = AngleForIndex(curIndex);

        return(Quaternion.AngleAxis(angle, Vector3.left));
    }
Esempio n. 4
0
    //creating the cards
    private IEnumerator CreateCards()
    {
        depth = -1f;

        //creating a limit of cards
        //Max limit is : initialCards varible
        for (int i = 0; i < initialCards; i++)
        {
            depth -= 0.001f;

            //Instantiating the card gameobject from a card prefab
            GameObject cardClone = Instantiate(cardPrefabs, new Vector3(0f, 8f, depth), Quaternion.AngleAxis(60f, Vector3.forward), deck);
            //putting the object name as index
            cardClone.name = i.ToString();

            //ssigning some sprite on the card gameobject
            int cardSpriteIndex = i;
            if (cardSpriteIndex >= images.Length)
            {
                cardSpriteIndex = Random.Range(0, images.Length);
            }
            cardClone.GetComponent <SpriteRenderer>().sprite = images [cardSpriteIndex];

            //rotate the card object
            LeanTween.rotateZ(cardClone, 0f, 0.1f);

            LeanTween.move(cardClone, new Vector3(0f, 0f, depth), 0.1f);


            //adding the card to all card list
            cardList.Add(cardClone);

            //created one poolObject list from where cards will be reused
            objectPoolList.Add(cardClone);

            //making some delay in creating so that the card will get time for little animate
            yield return(new WaitForSeconds(0.1f));

            //for swipe handling one script ia added
            cardClone.GetComponent <SwipeController> ().enabled = true;
        }
    }
Esempio n. 5
0
        protected override void OnDrag(Vector2 Pos)
        {
            var Angle = MathHelper.GetUnityAngle(DragBeginPos_, Pos);

            DragObj_.localRotation = Quaternion.AngleAxis(Angle, Vector3.forward);
        }
    void VerifiquePosicionamento()
    {
        int[] angulos = new int[9] {
            0, 30, -30, 45, -45, 60, -60, 90, -90
        };
        int     cont           = 0;
        bool    foi            = false;
        Vector3 charPosition   = GameController.g.Manager.transform.position;
        Vector3 baseDir        = charPosition - transform.position;
        Vector3 posDeInteresse = Vector3.zero;

        while (cont < 9 && !foi)
        {
            Vector3      dir = Quaternion.AngleAxis(angulos[cont], Vector3.forward) * baseDir;
            RaycastHit2D hit = Physics2D.Raycast(transform.position, dir, 100, 511);

            if (hit)
            {
                /*
                 * Debug.Log(cont+" raycast true "+hit.transform.name);
                 * Instantiate(mark1, hit.point, Quaternion.identity);
                 */
                Vector3 thisPoint = hit.point;
                hit = Physics2D.Linecast(hit.point + 0.25f * hit.normal, charPosition, 511);

                if (!hit)
                {
                    // Instantiate(transform.GetChild(0), thisPoint, Quaternion.identity);
                    moveDir = (thisPoint - transform.position).normalized;

                    foi = true;
                }
                else
                {
                    moveDir = dir;

                    /*
                     * Debug.Log(cont + "licast true: " + hit.transform.name);
                     * Instantiate(mark2, hit.point, Quaternion.identity);*/
                }
            }
            else
            {
                hit = Physics2D.Linecast(transform.position, charPosition, 511);
                if (hit)
                {
                    //Instantiate(transform.GetChild(0), charPosition, Quaternion.identity);

                    moveDir = -dir;
                    foi     = true;
                }
                else
                {
                    foi = false;
                }
            }

            cont++;
        }

        if (foi)
        {
            estado = EstadoDaqui.posicionandoParaAtirar;
        }
        else
        {
            moveDir = (transform.position - charPosition).normalized;
            estado  = EstadoDaqui.posicionandoEvasivamente;
            Invoke("VerificaDistanciaDeAtivacao", TEMPO_EM_EVASIVA);
        }
    }
        protected virtual void Impact(Thing hitThing)
        {
            bool flag = hitThing == null;

            if (flag)
            {
                Pawn pawn;
                bool flag2 = (pawn = (base.Position.GetThingList(base.Map).FirstOrDefault((Thing x) => x == this.assignedTarget) as Pawn)) != null;
                if (flag2)
                {
                    hitThing = pawn;
                }
            }
            if (hitThing != null)
            {
                damageEntities(hitThing, Mathf.RoundToInt(Rand.Range(this.def.projectile.GetDamageAmount(1, null) * .75f, this.def.projectile.GetDamageAmount(1, null) * 1.25f)));
            }
            TM_MoteMaker.ThrowShadowCleaveMote(this.ExactPosition, this.Map, 2f + (.4f * pwrVal), .05f, .1f, .3f, 0, (5f + pwrVal), this.directionAngle);
            TorannMagicDefOf.TM_SoftExplosion.PlayOneShot(new TargetInfo(this.ExactPosition.ToIntVec3(), this.pawn.Map, false));
            int num = GenRadial.NumCellsInRadius(1 + (.4f * pwrVal));

            Vector3 cleaveVector;
            IntVec3 intVec;

            for (int i = 0; i < num; i++)
            {
                cleaveVector = this.ExactPosition + (Quaternion.AngleAxis(-45, Vector3.up) * ((1.5f + (.5f * pwrVal)) * this.direction));
                intVec       = cleaveVector.ToIntVec3() + GenRadial.RadialPattern[i];
                //GenExplosion.DoExplosion(intVec, base.Map, .4f, TMDamageDefOf.DamageDefOf.TM_Shadow, this.launcher as Pawn, Mathf.RoundToInt((Rand.Range(.6f * this.def.projectile.GetDamageAmount(1,null), 1.1f * this.def.projectile.GetDamageAmount(1,null)) + (5f * pwrVal)) * this.arcaneDmg), this.def.projectile.soundExplode, def, null, null, 0f, 1, false, null, 0f, 0, 0.0f, true);

                if (intVec.IsValid && intVec.InBounds(this.Map))
                {
                    List <Thing> hitList = new List <Thing>();
                    hitList = intVec.GetThingList(base.Map);
                    for (int j = 0; j < hitList.Count; j++)
                    {
                        if (hitList[j] is Pawn && hitList[j] != this.pawn)
                        {
                            damageEntities(hitList[j], Mathf.RoundToInt((Rand.Range(this.def.projectile.GetDamageAmount(1, null) * .6f, this.def.projectile.GetDamageAmount(1, null) * .8f) * (float)(1f + .1 * pwrVal) * this.arcaneDmg)));
                        }
                    }
                }
                cleaveVector = this.ExactPosition + (Quaternion.AngleAxis(45, Vector3.up) * ((1.5f + (.5f * pwrVal)) * this.direction));
                intVec       = cleaveVector.ToIntVec3() + GenRadial.RadialPattern[i];
                //GenExplosion.DoExplosion(intVec, base.Map, .4f, TMDamageDefOf.DamageDefOf.TM_Shadow, this.launcher as Pawn, Mathf.RoundToInt((Rand.Range(.6f * this.def.projectile.GetDamageAmount(1,null), 1.1f * this.def.projectile.GetDamageAmount(1,null)) + (5f * pwrVal)) * this.arcaneDmg), this.def.projectile.soundExplode, def, null, null, 0f, 1, false, null, 0f, 0, 0.0f, true);

                if (intVec.IsValid && intVec.InBounds(this.Map))
                {
                    List <Thing> hitList = new List <Thing>();
                    hitList = intVec.GetThingList(base.Map);
                    for (int j = 0; j < hitList.Count; j++)
                    {
                        if (hitList[j] is Pawn && hitList[j] != this.pawn)
                        {
                            damageEntities(hitList[j], Mathf.RoundToInt((Rand.Range(this.def.projectile.GetDamageAmount(1, null) * .5f, this.def.projectile.GetDamageAmount(1, null) * .7f) * (float)(1f + .1 * pwrVal) * this.arcaneDmg)));
                        }
                    }
                }
                cleaveVector = this.ExactPosition + ((2 + (.3f * (float)pwrVal)) * this.direction);
                intVec       = cleaveVector.ToIntVec3() + GenRadial.RadialPattern[i];
                //GenExplosion.DoExplosion(intVec, base.Map, .4f, TMDamageDefOf.DamageDefOf.TM_Shadow, this.launcher as Pawn, Mathf.RoundToInt((Rand.Range(.6f*this.def.projectile.GetDamageAmount(1,null), 1.1f*this.def.projectile.GetDamageAmount(1,null)) + (5f * pwrVal)) * this.arcaneDmg), this.def.projectile.soundExplode, def, null, null, 0f, 1, false, null, 0f, 0, 0.0f, true);

                if (intVec.IsValid && intVec.InBounds(this.Map))
                {
                    List <Thing> hitList = new List <Thing>();
                    hitList = intVec.GetThingList(base.Map);
                    for (int j = 0; j < hitList.Count; j++)
                    {
                        if (hitList[j] is Pawn && hitList[j] != this.pawn)
                        {
                            damageEntities(hitList[j], Mathf.RoundToInt((Rand.Range(this.def.projectile.GetDamageAmount(1, null) * .5f, this.def.projectile.GetDamageAmount(1, null) * .7f) * (float)(1f + .1 * pwrVal) * this.arcaneDmg)));
                        }
                    }
                }
            }
            this.Destroy(DestroyMode.Vanish);
            //GenExplosion.DoExplosion(base.Position, base.Map, this.radius, TMDamageDefOf.DamageDefOf.TM_DeathBolt, this.launcher as Pawn, Mathf.RoundToInt((Rand.Range(.6f*this.def.projectile.GetDamageAmount(1,null), 1.1f*this.def.projectile.GetDamageAmount(1,null)) + (5f * pwrVal)) * this.arcaneDmg), this.def.projectile.soundExplode, def, null, null, 0f, 1, false, null, 0f, 0, 0.0f, true);
        }
        private void DrawCameraPosition(InteractionTrigger.Range range, int index)
        {
            if (range.cameraPosition.lookAtTarget == null)
            {
                return;
            }

            Vector3 labelPosition = range.cameraPosition.lookAtTarget.transform.position - Vector3.up * index * 0.05f;

            if (range.cameraPosition.direction == Vector3.zero)
            {
                Handles.Label(labelPosition, "Camera Position direction is Vector3.zero for Range" + index.ToString() + ": " + range.name);
                return;
            }
            if (range.cameraPosition.maxAngle <= 0f)
            {
                Handles.Label(labelPosition, "Camera Position max angle is zero for Range" + index.ToString() + ": " + range.name);
                return;
            }
            range.cameraPosition.maxDistance = Mathf.Max(range.cameraPosition.maxDistance, 0f);
            if (range.cameraPosition.maxDistance <= 0f)
            {
                Handles.Label(labelPosition, "Camera Position Max Distance is zero for Range" + index.ToString() + ": " + range.name);
                return;
            }

            Quaternion targetRotation = range.cameraPosition.GetRotation();
            Vector3    position       = range.cameraPosition.lookAtTarget.transform.position;

            Vector3 direction = targetRotation * range.cameraPosition.direction;

            direction = direction.normalized * range.cameraPosition.maxDistance;

            Handles.DrawLine(position, position + direction);
            Handles.DotCap(0, position + direction, Quaternion.identity, 0.005f);

            Handles.Label(position + direction * 1.1f, "Camera Position for Range " + index.ToString() + ": " + range.name);

            if (range.cameraPosition.maxAngle >= 180f)
            {
                return;
            }

            float r = Mathf.Sin(range.cameraPosition.maxAngle * Mathf.Deg2Rad) * range.cameraPosition.maxDistance;
            float d = Mathf.Cos(range.cameraPosition.maxAngle * Mathf.Deg2Rad) * range.cameraPosition.maxDistance;

            Quaternion rotation = targetRotation * Quaternion.LookRotation(range.cameraPosition.direction);

            Handles.CircleCap(0, position + direction.normalized * d, rotation, r);

            if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.camera != null)
            {
                //Vector3 c = Vector3.Cross(direction, SceneView.lastActiveSceneView.camera.transform.forward);
                Vector3 c = Vector3.Cross(direction, (range.cameraPosition.lookAtTarget.transform.position - SceneView.lastActiveSceneView.camera.transform.position).normalized);
                c = Vector3.Cross(direction, c);
                Quaternion dirRotation = Quaternion.AngleAxis(range.cameraPosition.maxAngle, c);
                Vector3    dir3        = dirRotation * direction;
                Handles.DrawLine(position, position + dir3);

                Vector3 dir4 = Quaternion.Inverse(dirRotation) * direction;
                Handles.DrawLine(position, position + dir4);

                Handles.DrawWireArc(position, -c, dir3, range.cameraPosition.maxAngle * 2, range.cameraPosition.maxDistance);
            }
        }
Esempio n. 9
0
 void Turn()
 {
     targetRotation    *= Quaternion.AngleAxis(rotateVel * turnInput * Time.deltaTime, Vector3.up);
     transform.rotation = targetRotation;
 }
    public override void GenerateMesh()
    {
        base.GenerateMesh();

        #region Vertices
        m_Verts = new Vector3[(m_RadialSegments + 1) * (m_Sides + 1)];
        float _2pi = Mathf.PI * 2f;
        for (int seg = 0; seg <= m_RadialSegments; seg++)
        {
            int currSeg = seg == m_RadialSegments ? 0 : seg;

            float   t1 = (float)currSeg / m_RadialSegments * _2pi;
            Vector3 r1 = new Vector3(Mathf.Cos(t1) * m_RadiusOuter, 0f, Mathf.Sin(t1) * m_RadiusOuter);

            for (int side = 0; side <= m_Sides; side++)
            {
                int currSide = side == m_Sides ? 0 : side;

                Vector3 normale = Vector3.Cross(r1, Vector3.up);
                float   t2      = (float)currSide / m_Sides * _2pi;
                Vector3 r2      = Quaternion.AngleAxis(-t1 * Mathf.Rad2Deg, Vector3.up) * new Vector3(Mathf.Sin(t2) * m_RadiusInner, Mathf.Cos(t2) * m_RadiusInner);

                m_Verts[side + seg * (m_Sides + 1)] = r1 + r2;
            }
        }
        #endregion

        #region normals
        m_Normals = new Vector3[m_Verts.Length];
        for (int seg = 0; seg <= m_RadialSegments; seg++)
        {
            int currSeg = seg == m_RadialSegments ? 0 : seg;

            float   t1 = (float)currSeg / m_RadialSegments * _2pi;
            Vector3 r1 = new Vector3(Mathf.Cos(t1) * m_RadiusOuter, 0f, Mathf.Sin(t1) * m_RadiusOuter);

            for (int side = 0; side <= m_Sides; side++)
            {
                m_Normals[side + seg * (m_Sides + 1)] = (m_Verts[side + seg * (m_Sides + 1)] - r1).normalized;
            }
        }
        #endregion

        #region UVs
        m_UVs = new Vector2[m_Verts.Length];
        for (int seg = 0; seg <= m_RadialSegments; seg++)
        {
            for (int side = 0; side <= m_Sides; side++)
            {
                m_UVs[side + seg * (m_Sides + 1)] = new Vector2((float)seg / m_RadialSegments, (float)side / m_Sides);
            }
        }
        #endregion

        #region Triangles
        int nbFaces     = m_Verts.Length;
        int nbTriangles = nbFaces * 2;
        int nbIndexes   = nbTriangles * 3;
        m_Tris = new int[nbIndexes];

        int i = 0;
        for (int seg = 0; seg <= m_RadialSegments; seg++)
        {
            for (int side = 0; side <= m_Sides - 1; side++)
            {
                int current = side + seg * (m_Sides + 1);
                int next    = side + (seg < (m_RadialSegments) ?(seg + 1) * (m_Sides + 1) : 0);

                if (i < m_Tris.Length - 6)
                {
                    m_Tris[i++] = current;
                    m_Tris[i++] = next;
                    m_Tris[i++] = next + 1;

                    m_Tris[i++] = current;
                    m_Tris[i++] = next + 1;
                    m_Tris[i++] = current + 1;
                }
            }
        }
        #endregion

        UpdateMeshVariables();
    }
        private void DrawCharacterPosition(InteractionTrigger.Range range, int index)
        {
            Vector3 labelPosition = script.transform.position - Vector3.up * index * 0.05f;

            if (!range.characterPosition.use)
            {
                Handles.Label(labelPosition, "Character Position is not used for Range " + index.ToString() + ": " + range.name);
                return;
            }
            range.characterPosition.radius = Mathf.Max(range.characterPosition.radius, 0f);
            if (range.characterPosition.radius <= 0f)
            {
                Handles.Label(labelPosition, "Character Position radius is zero for Range " + index.ToString() + ": " + range.name);
                return;
            }
            if (range.characterPosition.maxAngle <= 0f)
            {
                Handles.Label(labelPosition, "Character Position max angle is zero for Range " + index.ToString() + ": " + range.name);
                return;
            }

            Vector3 f = script.transform.forward;

            if (range.characterPosition.fixYAxis)
            {
                f.y = 0f;
            }
            if (f == Vector3.zero)
            {
                Handles.Label(script.transform.position - Vector3.up * index * 0.05f, "Invalid rotation of InteractionTrigger for Range " + index.ToString() + ": " + range.name);
                return;                 // Singularity
            }

            Quaternion triggerRotation = Quaternion.LookRotation(f, (range.characterPosition.fixYAxis? Vector3.up: script.transform.up));

            Vector3 position = script.transform.position + triggerRotation * range.characterPosition.offset3D;

            Vector3 direction = triggerRotation * range.characterPosition.direction3D;

            Quaternion rotation = direction == Vector3.zero? triggerRotation: Quaternion.LookRotation(direction, (range.characterPosition.fixYAxis? Vector3.up: script.transform.up));
            Vector3    up       = rotation * Vector3.up;
            Vector3    forward  = rotation * Vector3.forward;

            Handles.DrawWireDisc(position, up, range.characterPosition.radius);

            if (range.characterPosition.orbit)
            {
                float mag = range.characterPosition.offset.magnitude;

                if (mag - range.characterPosition.radius > 0f)
                {
                    Handles.DrawWireDisc(script.transform.position, up, mag - range.characterPosition.radius);
                }

                Handles.DrawWireDisc(script.transform.position, up, mag + range.characterPosition.radius);
            }

            Vector3    x = forward * range.characterPosition.radius;
            Quaternion q = Quaternion.AngleAxis(-range.characterPosition.maxAngle, up);

            Vector3 dir = q * x;

            if (direction != Vector3.zero && range.characterPosition.maxAngle < 180f)
            {
                Handles.DrawLine(position, position + x);
                Handles.DotCap(0, position + x, Quaternion.identity, range.characterPosition.radius * 0.01f);
            }

            Handles.Label(position - Vector3.up * index * 0.05f, "Character Position for Range " + index.ToString() + ": " + range.name);

            Color color       = Handles.color;
            Color transparent = new Color(color.r, color.g, color.b, 0.3f);

            Handles.color = transparent;

            Handles.DrawSolidArc(position, up, dir, range.characterPosition.maxAngle * 2f, range.characterPosition.radius);

            Handles.color = color;
        }
 void Update()
 {
     transform.localRotation = Quaternion.AngleAxis(angularVelocity * Time.deltaTime, rotationAxis) * transform.localRotation;
 }
Esempio n. 13
0
        /// <summary>
        /// Move the object based on the current velocity.
        /// </summary>
        /// <param name="position">The current position of the object. Passed by reference so the updated position can be set.</param>
        /// <param name="rotation">The current rotation of the object.</param>
        /// <returns>True if the position was updated or the movement has settled.</returns>
        private bool Move(ref Vector3 position, Quaternion rotation)
        {
            // The object can't move if the movement and rotation has settled.
            if (m_MovementSettled && m_RotationSettled && m_SettleThreshold > 0)
            {
                return(true);
            }

            // Stop moving if the velocity is less than a minimum threshold and the object is on the ground.
            if (m_Velocity.sqrMagnitude < m_SettleThreshold && m_RotationSettled)
            {
                // The object should be on the ground before the object has settled.
                if (SingleCast(position, rotation, m_NormalizedGravity * c_ColliderSpacing))
                {
                    m_MovementSettled = true;
                    return(true);
                }
            }

            var deltaTime = m_TimeScale * Time.fixedDeltaTime * Time.timeScale;

            // The object hasn't settled yet - move based on the velocity.
            m_Velocity += m_Gravity * deltaTime;
            m_Velocity *= Mathf.Clamp01(1 - m_Damping * deltaTime);

            // If the object hits an object then it should either reflect off of that object or stop moving.
            var targetPosition = position + m_Velocity * m_Speed * deltaTime;
            var direction      = targetPosition - position;

            if (SingleCast(position, rotation, direction))
            {
                if (m_RaycastHit.transform.gameObject.layer == LayerManager.MovingPlatform)
                {
                    if (m_RaycastHit.transform != m_Platform)
                    {
                        m_Platform = m_RaycastHit.transform;
                        m_PlatformRelativePosition = m_Platform.InverseTransformPoint(position);
                        m_PrevPlatformRotation     = m_Platform.rotation;
                    }
                }
                else
                {
                    m_Platform = null;
                }

                // If the object has settled but not disabled a collision will occur every frame. Prevent the effects from playing because of this.
                if (!m_InCollision)
                {
                    m_InCollision = true;
                    OnCollision(m_RaycastHit);
                }

                if (m_CollisionMode == CollisionMode.Collide)
                {
                    m_Velocity        = Vector3.zero;
                    m_Torque          = Vector3.zero;
                    m_MovementSettled = true;
                    enabled           = false;
                    return(true);
                }
                else if (m_CollisionMode != CollisionMode.Ignore)     // Reflect and Random Reflect.
                {
                    Vector3 velocity;
                    if (m_CollisionMode == CollisionMode.RandomReflect)
                    {
                        // Add ramdomness to the bounce.
                        // This mode should not be used over the network unless it doesn't matter if the object is synchronized (such as a shell).
                        velocity = Quaternion.AngleAxis(Random.Range(-70, 70), m_RaycastHit.normal) * m_Velocity;
                    }
                    else     // Reflect.
                    {
                        velocity = m_Velocity;
                    }

                    // The bounce strenght is dependent on the physic material.
                    var dynamicFrictionValue = m_Collider != null?Mathf.Clamp01(1 - MathUtility.FrictionValue(m_Collider.material, m_RaycastHit.collider.material, true)) : 0;

                    // Update the velocity to the reflection direction.
                    m_Velocity = Vector3.Reflect(velocity, m_RaycastHit.normal) * dynamicFrictionValue * m_ReflectMultiplier;
                    if (m_Velocity.magnitude < m_StartSidewaysVelocityMagnitude)
                    {
                        m_MovementSettled = true;
                    }
                    m_Collided = true;
                    return(false);
                }
            }
            else
            {
                m_Platform    = null;
                m_InCollision = false;
            }
            position = targetPosition;
            return(true);
        }
Esempio n. 14
0
    /// <summary>
    /// Must return a list of floats corresponding to the state the agent is in. If the state space type is discrete,
    /// return a list of length 1 containing the float equivalent of your state.
    /// </summary>
    /// <returns></returns>
    public override List <float> CollectState()
    {
        List <float> state = new List <float>();

        // New implementation, raycasts in 8 directions with information on what they hit
        RaycastHit2D[] rays = new RaycastHit2D[numRays];
        // New loop
        for (int i = 0; i < rays.Length; i++)
        {
            rays[i] = Physics2D.Raycast(gameObject.transform.position, Quaternion.AngleAxis((360f / rays.Length) * i, Vector3.forward) * transform.up, sightDistance);
            // Debug
            if (debug)
            {
                if (rays[i])
                {
                    Debug.DrawLine(gameObject.transform.position, rays[i].point, rays[i].collider.tag == "Gold" ? Color.green : Color.blue);
                }
                else
                {
                    Debug.DrawLine(gameObject.transform.position, (gameObject.transform.position + (Quaternion.AngleAxis((360f / rays.Length) * i, Vector3.forward) * transform.up).normalized * sightDistance));
                }
            }
        }
        for (int i = 0; i < rays.Length; i++)
        {
            state.Add(rays[i].distance / sightDistance);
            // Add information about what was hit
            if (rays[i])
            {
                // Is it a Wall? Gold? Enemy?
                state.Add(rays[i].collider.tag == "Enemy" ? 1.0f : 0.0f);
                state.Add(rays[i].collider.tag == "Wall" ? 1.0f : 0.0f);
                state.Add(rays[i].collider.tag == "Gold" ? 1.0f : 0.0f);
            }
            else
            {
                state.Add(0.0f);
                state.Add(0.0f);
                state.Add(0.0f);
            }
        }
        // Could we attack if we needed to?
        float cd = (Time.time - shooter.GetComponent <ArcherAgent>().lastShot) / shooter.GetComponent <ArcherAgent>().shotDelay;

        state.Add(cd >= 1 ? 1 : 0);
        return(state);
    }
Esempio n. 15
0
        public void CleanGraphics(Thing filth)
        {
            TM_FleckMaker.ThrowGenericFleck(FleckDefOf.MicroSparks, this.ExactPosition, this.Map, Rand.Range(.3f, .5f), .6f, .2f, .4f, Rand.Range(-400, -100), .3f, Rand.Range(0, 360), Rand.Range(0, 360));
            Vector3 angle = TM_Calc.GetVector(filth.DrawPos, this.ExactPosition);

            TM_MoteMaker.ThrowGenericMote(TorannMagicDefOf.Mote_ThickDust, filth.DrawPos, this.Map, Rand.Range(.4f, .6f), .1f, .05f, .25f, -200, 2, (Quaternion.AngleAxis(90, Vector3.up) * angle).ToAngleFlat(), Rand.Range(0, 360));
        }
Esempio n. 16
0
		public static Quaternion OrientToLocalPosition(Bone2D bone, Vector3 localPosition, bool freezeChildren, string undoName, bool recordObject)
		{
			Quaternion l_deltaRotation = Quaternion.identity;

			if(bone && localPosition.sqrMagnitude > 0f)
			{
				List<Vector3> l_childPositions = new List<Vector3>(bone.transform.childCount);
				List<Transform> l_children = new List<Transform>(bone.transform.childCount);

				if(freezeChildren)
				{
					Transform l_mainChild = null;

					if(bone.child)
					{
						l_mainChild = bone.child.transform;
					}

					foreach(Transform child in bone.transform)
					{
						if(child != l_mainChild)
						{
							if(recordObject)
							{
								Undo.RecordObject(child,undoName);
							}else{
								Undo.RegisterCompleteObjectUndo(child,undoName);
							}
							
							l_children.Add(child);
							l_childPositions.Add(child.position);
						}
					}	
				}

				Quaternion l_deltaInverseRotation = Quaternion.identity;
				
				float angle = Mathf.Atan2(localPosition.y,localPosition.x) * Mathf.Rad2Deg;
				
				if(recordObject)
				{
					Undo.RecordObject(bone.transform,undoName);
				}else{
					Undo.RegisterCompleteObjectUndo(bone.transform,undoName);
				}
				
				l_deltaRotation = Quaternion.AngleAxis(angle, Vector3.forward);
				l_deltaInverseRotation = Quaternion.Inverse(l_deltaRotation);
				
				bone.transform.localRotation *= l_deltaRotation;
				FixLocalEulerHint(bone.transform);

				for (int i = 0; i < l_children.Count; i++)
				{
					Transform l_child = l_children[i];
					
					l_child.position = l_childPositions[i];
					l_child.localRotation *= l_deltaInverseRotation;
					FixLocalEulerHint(l_child);

					EditorUtility.SetDirty (l_child);
				}
				
				EditorUtility.SetDirty(bone.transform);
			}

			return l_deltaRotation;
		}
Esempio n. 17
0
        public override void Tick()
        {
            //base.Tick();

            age++;
            this.searchDelay--;
            Vector3 exactPosition = this.ExactPosition;

            this.ticksToImpact--;
            bool flag = !this.ExactPosition.InBounds(base.Map);

            if (flag)
            {
                this.ticksToImpact++;
                base.Position = this.ExactPosition.ToIntVec3();
                this.Destroy(DestroyMode.Vanish);
            }
            else
            {
                base.Position = this.ExactPosition.ToIntVec3();
                bool flag2 = this.ticksToImpact <= 0;
                if (flag2)
                {
                    if (this.age < this.duration)
                    {
                        this.origin        = this.ExactPosition;
                        this.destination   = FindNearestFilth(this.origin);
                        this.ticksToImpact = this.StartingTicksToImpact;
                    }
                    else
                    {
                        bool flag3 = this.DestinationCell.InBounds(base.Map);
                        if (flag3)
                        {
                            base.Position = this.DestinationCell;
                        }
                        this.ImpactSomething();
                    }
                }
                if (Find.TickManager.TicksGame % 4 == 0)
                {
                    Vector3 rndVec = this.ExactPosition;
                    rndVec.x += Rand.Range(-1f, 1f);
                    rndVec.z += Rand.Range(-1f, 1f);
                    Vector3 angle = TM_Calc.GetVector(rndVec, this.ExactPosition);
                    TM_MoteMaker.ThrowGenericMote(ThingDefOf.Gas_Smoke, rndVec, this.Map, Rand.Range(.8f, 1.5f), .1f, .05f, .15f, -300, 2, (Quaternion.AngleAxis(90, Vector3.up) * angle).ToAngleFlat(), Rand.Range(0, 360));
                }
                if (this.searchDelay < 0)
                {
                    if (this.destination != default(Vector3))
                    {
                        this.searchDelay = Rand.Range(10, 20);
                        CleanFilth();
                    }
                }
            }
        }
Esempio n. 18
0
        bool DoTwoHandedScaling(ConsumeControlDelegate consumeControl)
        {
            foreach (var linkedObject in linkedObjects)
            {
                if (((LocomotionTool)linkedObject).m_Rotating)
                    return false;
            }

            if (this.IsSharedUpdater(this))
            {
                var crawl = m_LocomotionInput.crawl;
                if (crawl.isHeld)
                {
                    if (m_AllowScaling)
                    {
                        var otherGripHeld = false;
                        foreach (var linkedObject in linkedObjects)
                        {
                            var otherLocomotionTool = (LocomotionTool)linkedObject;
                            if (otherLocomotionTool == this)
                                continue;

                            var otherLocomotionInput = otherLocomotionTool.m_LocomotionInput;
                            if (otherLocomotionInput == null) // This can occur if crawl is pressed when EVR is opened
                                continue;

                            var otherCrawl = otherLocomotionInput.crawl;
                            if (otherCrawl.isHeld)
                            {
                                otherGripHeld = true;
                                consumeControl(crawl);
                                consumeControl(otherCrawl);

                                // Also consume thumbstick axes to disable radial menu
                                consumeControl(m_LocomotionInput.horizontal);
                                consumeControl(m_LocomotionInput.vertical);
                                consumeControl(otherLocomotionInput.horizontal);
                                consumeControl(otherLocomotionInput.vertical);

                                var thisPosition = cameraRig.InverseTransformPoint(rayOrigin.position);
                                var otherRayOrigin = otherLocomotionTool.rayOrigin;
                                var otherPosition = cameraRig.InverseTransformPoint(otherRayOrigin.position);
                                var distance = Vector3.Distance(thisPosition, otherPosition);

                                this.AddRayVisibilitySettings(rayOrigin, this, false, false);
                                this.AddRayVisibilitySettings(otherRayOrigin, this, false, false);

                                var rayToRay = otherPosition - thisPosition;
                                var midPoint = thisPosition + rayToRay * 0.5f;

                                rayToRay.y = 0; // Use for yaw rotation

                                var pivotYaw = MathUtilsExt.ConstrainYawRotation(cameraRig.rotation);

                                if (!m_Scaling)
                                {
                                    m_StartScale = this.GetViewerScale();
                                    m_StartDistance = distance;
                                    m_StartMidPoint = pivotYaw * midPoint * m_StartScale;
                                    m_StartPosition = cameraRig.position;
                                    m_StartDirection = rayToRay;
                                    m_StartYaw = cameraRig.rotation.eulerAngles.y;

                                    otherLocomotionTool.m_Scaling = true;
                                    otherLocomotionTool.m_Crawling = false;
                                    otherLocomotionTool.m_StartCrawling = false;

                                    m_ViewerScaleVisuals.leftHand = rayOrigin;
                                    m_ViewerScaleVisuals.rightHand = otherRayOrigin;
                                    m_ViewerScaleVisuals.gameObject.SetActive(true);

                                    foreach (var obj in linkedObjects)
                                    {
                                        var locomotionTool = (LocomotionTool)obj;
                                        locomotionTool.HideScaleFeedback();
                                        locomotionTool.HideRotateFeedback();
                                        locomotionTool.HideMainButtonFeedback();
                                        locomotionTool.ShowResetScaleFeedback();
                                    }
                                }

                                m_Scaling = true;
                                m_StartCrawling = false;
                                m_Crawling = false;

                                var currentScale = Mathf.Clamp(m_StartScale * (m_StartDistance / distance), k_MinScale, k_MaxScale);

                                var scaleReset = m_LocomotionInput.scaleReset;
                                var scaleResetHeld = scaleReset.isHeld;
                                if (scaleResetHeld)
                                    consumeControl(scaleReset);

                                var otherScaleReset = otherLocomotionInput.scaleReset;
                                var otherScaleResetHeld = otherScaleReset.isHeld;
                                if (otherScaleResetHeld)
                                    consumeControl(otherScaleReset);

                                // Press both thumb buttons to reset scale
                                if (scaleResetHeld && otherScaleResetHeld)
                                {
                                    m_AllowScaling = false;

                                    rayToRay = otherRayOrigin.position - rayOrigin.position;
                                    midPoint = rayOrigin.position + rayToRay * 0.5f;
                                    var currOffset = midPoint - cameraRig.position;

                                    cameraRig.position = midPoint - currOffset / currentScale;
                                    cameraRig.rotation = Quaternion.AngleAxis(m_StartYaw, Vector3.up);

                                    ResetViewerScale();
                                }

                                var worldReset = m_LocomotionInput.worldReset;
                                var worldResetHeld = worldReset.isHeld;
                                if (worldResetHeld)
                                    consumeControl(worldReset);

                                var otherWorldReset = otherLocomotionInput.worldReset;
                                var otherWorldResetHeld = otherWorldReset.isHeld;
                                if (otherWorldResetHeld)
                                    consumeControl(otherWorldReset);

                                // Press both triggers to reset to origin
                                if (worldResetHeld && otherWorldResetHeld)
                                {
                                    m_AllowScaling = false;
                                    cameraRig.position = VRView.headCenteredOrigin;
                                    cameraRig.rotation = Quaternion.identity;

                                    ResetViewerScale();
                                }

                                if (m_AllowScaling)
                                {
                                    var yawSign = Mathf.Sign(Vector3.Dot(Quaternion.AngleAxis(90, Vector3.down) * m_StartDirection, rayToRay));
                                    var currentYaw = m_StartYaw + Vector3.Angle(m_StartDirection, rayToRay) * yawSign;
                                    var currentRotation = Quaternion.AngleAxis(currentYaw, Vector3.up);
                                    midPoint = currentRotation * midPoint * currentScale;

                                    cameraRig.position = m_StartPosition + m_StartMidPoint - midPoint;
                                    cameraRig.rotation = currentRotation;

                                    this.SetViewerScale(currentScale);
                                }
                                break;
                            }
                        }

                        if (!otherGripHeld)
                            CancelScale();
                    }
                }
                else
                {
                    CancelScale();
                }
            }

            return m_Scaling;
        }
Esempio n. 19
0
    void Update()
    {
        if (Time.timeScale != 0)
        {
            //Point the player towards the mouse position
            Vector3 dir   = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
            float   angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
            transform.rotation = Quaternion.AngleAxis(angle + 90, Vector3.forward);

            //Move the player
            Vector2 moveAmount = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
            transform.Translate(moveAmount * moveSpeed * Time.deltaTime, Space.World);

            //Constrain the player to within the screen
            if (transform.position.y > GameMaster.instance.screenTopEdge)
            {
                transform.position = new Vector2(transform.position.x, GameMaster.instance.screenTopEdge);
            }
            if (transform.position.y < GameMaster.instance.screenBottomEdge + 1)
            {
                transform.position = new Vector2(transform.position.x, GameMaster.instance.screenBottomEdge + 1);
            }
            if (transform.position.x < GameMaster.instance.screenLeftEdge)
            {
                transform.position = new Vector2(GameMaster.instance.screenLeftEdge, transform.position.y);
            }
            if (transform.position.x > GameMaster.instance.screenRightEdge)
            {
                transform.position = new Vector2(GameMaster.instance.screenRightEdge, transform.position.y);
            }

            //Attack
            attackInterval -= Time.deltaTime;
            if (attackSpeedPowerupActive == true)
            {
                attackInterval = 0;
            }

            //Left click
            if (Input.GetMouseButton(0) && attackInterval <= 0)
            {
                //Ultra super hyper attack??
                if (catPawPowerupActive && attackSpeedPowerupActive)
                {
                    GameObject newFireball = Instantiate(fireballPrefab, transform.position, Quaternion.identity);
                    newFireball.transform.rotation = transform.rotation;

                    if (tripleShotPowerupActive == true)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            GameObject moreFireball = Instantiate(fireballPrefab, transform.position, Quaternion.identity);
                            moreFireball.transform.rotation = transform.rotation;
                        }
                    }

                    GameObject newCatpaw = Instantiate(catPawPrefab, transform.position, Quaternion.identity);
                    newCatpaw.transform.rotation = transform.rotation;
                }

                //Cat paw attack
                else if (catPawPowerupActive)
                {
                    GameObject newCatpaw = Instantiate(catPawPrefab, transform.position, Quaternion.identity);
                    newCatpaw.transform.rotation = transform.rotation;
                    attackInterval = 0.5f;
                }

                //Attack speed active
                else if (attackSpeedPowerupActive)
                {
                    GameObject newFireball = Instantiate(fireballPrefab, transform.position, Quaternion.identity);
                    newFireball.transform.rotation = transform.rotation;

                    if (tripleShotPowerupActive == true)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            GameObject moreFireball = Instantiate(fireballPrefab, transform.position, Quaternion.identity);
                            moreFireball.transform.rotation = transform.rotation;
                        }
                    }
                }

                //Normal fireball attack
                else
                {
                    GameObject newFireball = Instantiate(fireballPrefab, transform.position, Quaternion.identity);
                    newFireball.transform.rotation = transform.rotation;
                    attackInterval = attackIntervalLength;

                    if (tripleShotPowerupActive == true)
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            GameObject moreFireball = Instantiate(fireballPrefab, transform.position, Quaternion.identity);
                            moreFireball.transform.rotation = transform.rotation;
                        }
                    }
                }
            }

            if (Input.GetKeyDown(KeyCode.Space))
            {
                GameplayUI.instance.UseBlank();
            }
        }
    }
Esempio n. 20
0
 //Generate the extrude array
 public void generate()
 {
     if (arrowTipMode == ArrowTipMode.None) return;
     //set default functions if not set
     ArrowPath.validateAnimationFunction(widthFunction, 1, 0);
     ArrowPath.validateAnimationFunction(heightFunction, 1, 0);
     ArrowPath.validateAnimationFunction(rotateFunction, 0, 0);
     ArrowPath.validateAnimationFunction(shapeFunction, 0, 0);
     if (pathLength == 0) return;
     extrudePoints = new Matrix4x4[path.Count];
     primitives = new Primitive[path.Count];
     openClosed = new int[path.Count];
     float currentLength = 0;
     extrudePoints[0] = new Matrix4x4();
     //Calculate the first extrude
     Vector3 pathDiff = direction * (path[1] - path[0]);
     arrowPath.defaultRotateAngle = defaultRotateAngle;
     Quaternion nextDirectionX;
     Quaternion nextDirectionY;
     Quaternion extrudeDirectionX;
     Quaternion extrudeDirectionY;
     Quaternion lastDirectionX;
     Quaternion lastDirectionY;
     //First rotation depends on first path point direction and rotation from main path
     nextDirectionX = arrowPath.calculateUpDownQuaternion(pathDiff);
     nextDirectionY = arrowPath.calculateLeftRightQuaternion(pathDiff);
     lastDirectionX = nextDirectionX;
     lastDirectionY = nextDirectionY;
     float propagatingRotateAngle = 0;
     if (direction == -1)
     {
         propagatingRotateAngle = arrowPath.rotateFunction.Evaluate(0);
     }
     else
     {
         propagatingRotateAngle = arrowPath.rotateFunction.Evaluate(arrowPath.rotationFunctionLength);
     }
     extrudePoints[0].SetTRS(path[0], Quaternion.AngleAxis((rotateFunction.Evaluate(currentLength / pathLength * rotationFunctionLength) + propagatingRotateAngle) * 360, nextDirectionY * nextDirectionX * Vector2.up) * nextDirectionY * nextDirectionX, new Vector3(widthFunction.Evaluate(currentLength / pathLength * widthFunctionLength) * size.x, 1, heightFunction.Evaluate(currentLength / pathLength * heightFunctionLength) * size.z));
     //choose shape
     int primitiveIndex = (int)shapeFunction.Evaluate(0);
     if (primitiveIndex < 0) primitiveIndex = 0;
     if (primitiveIndex >= templatePrimitives.primitivesList.Count) primitiveIndex = templatePrimitives.primitivesList.Count - 1;
     primitives[0] = templatePrimitives.primitivesList[primitiveIndex];
     openClosed[0] = (getClosed()) ? 0 : 1;
     //Calculate the other extrude points
     for (int i = 1; i < path.Count; i++)
     {
         currentLength += (path[i] - path[i - 1]).magnitude;
         extrudePoints[i] = new Matrix4x4();
         float scaleWidthByAngle = 1f;
         float scaleHeightByAngle = 1f;
         if (i < path.Count - 1)
         {
             pathDiff = direction * (path[i + 1] - path[i]);
             nextDirectionX = arrowPath.calculateUpDownQuaternion(pathDiff);
             nextDirectionY = arrowPath.calculateLeftRightQuaternion(pathDiff);
             //Points depend on previous and next point directions
             if (Quaternion.Angle(lastDirectionX, nextDirectionX) < 0.1f)
             {
                 extrudeDirectionX = nextDirectionX;
             }
             else
             {
                 extrudeDirectionX = Quaternion.Lerp(lastDirectionX, nextDirectionX, 0.5f);
             }
             if (Quaternion.Angle(lastDirectionY, nextDirectionY) < 0.1f)
             {
                 extrudeDirectionY = nextDirectionY;
             }
             else
             {
                 extrudeDirectionY = Quaternion.Lerp(lastDirectionY, nextDirectionY, 0.5f);
             }
             //Scale depends on angle between points
             scaleWidthByAngle = Mathf.Abs(Mathf.Cos(Mathf.Deg2Rad * Vector3.Angle(lastDirectionY * Vector3.forward, nextDirectionY * Vector3.forward) / 2));
             scaleWidthByAngle = (scaleWidthByAngle < 0.5f) ? 1 : 1 / scaleWidthByAngle;
             scaleHeightByAngle = Mathf.Abs(Mathf.Cos(Mathf.Deg2Rad * Vector3.Angle(lastDirectionX * Vector3.up, nextDirectionX * Vector3.up) / 2));
             scaleHeightByAngle = (scaleHeightByAngle < 0.5f) ? 1 : 1 / scaleHeightByAngle;
         }
         else
         {
             pathDiff = direction * (path[i] - path[i - 1]);
             nextDirectionX = arrowPath.calculateUpDownQuaternion(pathDiff);
             nextDirectionY = arrowPath.calculateLeftRightQuaternion(pathDiff);
             extrudeDirectionX = nextDirectionX;
             extrudeDirectionY = nextDirectionY;
         }
         extrudePoints[i].SetTRS(path[i], Quaternion.AngleAxis((rotateFunction.Evaluate(currentLength / pathLength * rotationFunctionLength) + propagatingRotateAngle) * 360, extrudeDirectionY * extrudeDirectionX * Vector3.up) * extrudeDirectionY * extrudeDirectionX, new Vector3(scaleWidthByAngle * widthFunction.Evaluate(currentLength / pathLength * widthFunctionLength) * size.x, 1, scaleHeightByAngle * heightFunction.Evaluate(currentLength / pathLength * heightFunctionLength) * size.z));
         primitiveIndex = (int)(shapeFunction.Evaluate(currentLength / pathLength * shapeFunctionLength));
         if (primitiveIndex < 0) primitiveIndex = 0;
         if (primitiveIndex >= templatePrimitives.primitivesList.Count) primitiveIndex = templatePrimitives.primitivesList.Count - 1;
         primitives[i] = templatePrimitives.primitivesList[primitiveIndex];
         openClosed[i] = 1;
         lastDirectionX = nextDirectionX;
         lastDirectionY = nextDirectionY;
     }
     openClosed[path.Count - 1] = 2;
 }
Esempio n. 21
0
 public void CalibrateAzimuth()
 {
     reference = Quaternion.AngleAxis(-GetAzimuth(Last), Vector3.up);
 }
Esempio n. 22
0
 // Update is called once per frame
 void Update()
 {
     transform.rotation = Quaternion.AngleAxis(GetComponentInParent <BulletMovement>().getDirection() * Mathf.Rad2Deg, Vector3.back);
 }
    IEnumerator _Coro_Process()
    {
        tk2dSpriteAnimation s;

        //云母出现
        AniSpr_YunMu.AnimationEventTriggered += Handle_YunMuAnimating;

        //出蝴蝶鱼 米字 方向45度一格
        int hudieNum       = 3;
        int hudieInstedNum = 0;

        int[] rndArray = new int[] { 0, 1, 2, 3, 4, 5, 6, 7 };
        System.Array.Sort(rndArray, (a, b) => { return(Random.Range(0, 3) - 1); });

        while (hudieInstedNum < hudieNum)
        {
            yield return(new WaitForSeconds(1F));

            Fish fishHuDie = Instantiate(Prefab_FirstFish) as Fish;
            fishHuDie.ClearAI();
            fishHuDie.transform.parent        = transform;
            fishHuDie.transform.localPosition = Vector3.zero;

            fishHuDie.transform.rotation = Quaternion.AngleAxis(45F * rndArray[hudieInstedNum], Vector3.forward);


            //特殊版本最后一条蝴蝶方向偏移
            if (hudieInstedNum == hudieNum - 1)
            {
                fishHuDie.transform.rotation *= Quaternion.AngleAxis(-15F, Vector3.forward);
            }


            fishHuDie.swimmer.Go();
            fishHuDie.swimmer.Speed = SpeedFirstFish;
            ++hudieInstedNum;
        }



        //云母fadeOut
        yield return(new WaitForSeconds(1F));

        StartCoroutine(_Coro_YunMuAlphaDown());


        //散花出鱼
        int flowEmitNum    = FlowerEmitDatas.Length;
        int curflowEmitNum = 0;
        //rndArray = new int[FlowerEmitDatas.Length];
        //for(int i = 0; i != rndArray.Length; ++i)
        //    rndArray[i] = i;
        //System.Array.Sort(rndArray,(a,b)=>{return Random.Range(0,3)-1;});
        float baseRotateAngle = 90F;

        float depth = 0F;

        while (curflowEmitNum < flowEmitNum)
        {
            FlowerEmitData emitData = FlowerEmitDatas[curflowEmitNum];

            float emitElapse = 0F;
            //一群
            while (emitElapse < emitData.EmitUseTime)
            {
                //6方向一起出
                for (int i = 0; i != 6; ++i)
                {
                    Fish f = Instantiate(emitData.PrefabFish) as Fish;
                    f.ClearAI();
                    f.transform.parent = transform;

                    f.transform.localRotation = Quaternion.AngleAxis(baseRotateAngle + 60F * i + Random.Range(-15F, 15F), Vector3.forward);
                    f.transform.localPosition = new Vector3(0F, 0F, depth) + f.transform.up * 0.02F;
                    depth += 0.001F;

                    f.swimmer.Speed = emitData.SwimSpd;
                    f.swimmer.Go();
                }

                emitElapse += emitData.EmitInterval;
                yield return(new WaitForSeconds(emitData.EmitInterval));
            }

            baseRotateAngle += 45F;
            ++curflowEmitNum;
            yield return(new WaitForSeconds(1F));
        }


        //等待清鱼,[过期]改用时间作限制
        while (GameMain.Singleton.NumFishAlive != 0)
        {
            yield return(0);
        }
        EndPrelude();
    }
Esempio n. 24
0
 public static void SetTfm(Transform transform, float x, float y, float angle)
 {
     transform.position = new Vector3(x, 0, y);
     transform.rotation = Quaternion.AngleAxis(Mathf.Rad2Deg * angle,
                                               Vector3.down);
 }
        /*
         * protected double GetWorldHeading(Transform anchor, Transform objTransform)
         * {
         *  var fwd = GetTransformForward(anchor, objTransform);
         *
         *  var z = Vector3.Dot(fwd, Vector3.forward);
         *
         *  return Math.Acos(z) * 180 / Math.PI;
         * }*/

        protected virtual void SetSpawnPosition(SceneARWorldObject worldObject, Camera worldCamera, Transform worldAnchor)
        {
            var gameObj = worldObject.GameObject;

            gameObj.transform.localScale    = Vector3.one;
            gameObj.transform.localRotation = Quaternion.identity;

            if (worldObject.Position is RelativeWorldPosition)
            {
                var relPos = worldObject.Position as RelativeWorldPosition;

                if (worldObject.AnchorObject != null)
                {
                    var y = (float)relPos.Elevation;
                    var x = (float)(relPos.Distance * Math.Sin(relPos.Angle));
                    var z = (float)(relPos.Distance * Math.Cos(relPos.Angle));

                    var offset = new Vector3(x, y, z);

                    var objPos = worldObject.AnchorObject.GameObject.transform.position + offset;

                    var cam = ARWorld.Instance.GetWorldObjectCamera(worldObject.AnchorObject);

                    var camRel = objPos - cam.transform.position;

                    objPos = worldCamera.transform.position + camRel;

                    //var anchorCamHdg = GetWorldHeading(cam.transform);

                    gameObj.transform.rotation = worldObject.GameObject.transform.rotation;
                    gameObj.transform.position = objPos;
                }
                else
                {
                    var hdg = GetWorldHeading(worldCamera.transform);

                    var angle  = hdg + relPos.Angle;
                    var rangle = angle * Mathf.Deg2Rad;

                    m_logger.Debug("Using relative position with angle={0} and cam hdg={1}",
                                   relPos.Angle, hdg);

                    var y = (float)relPos.Elevation;
                    var x = (float)(relPos.Distance * Math.Sin(rangle));
                    var z = (float)(relPos.Distance * Math.Cos(rangle));

                    var spawnPos = worldCamera.transform.position + new Vector3(x, y, z);

                    gameObj.transform.rotation = Quaternion.AngleAxis((float)angle, Vector3.up);

                    gameObj.transform.position = spawnPos;
                }
            }
            else if (worldObject.Position is FixedWorldPosition)
            {
                var fixPos = worldObject.Position as FixedWorldPosition;

                var y = (float)fixPos.Position.Y;
                var x = (float)fixPos.Position.X;
                var z = (float)fixPos.Position.Z;

                var spawnPos = new Vector3(x, y, z);

                gameObj.transform.localPosition = spawnPos;
            }
        }
Esempio n. 26
0
    private void CheckSensors()
    {
        Vector3 sensorStartPos = transform.position;

        sensorStartPos.y += sensorHeight;
        Vector3 forwardDir = transform.forward;

        sensorStartPos += forwardDir * sensorX;

        avoiding     = false;
        accelerating = true;
        breaking     = false;
        float      avoidNum = 0f;
        RaycastHit hit;

        //center sensor
        if (Physics.Raycast(sensorStartPos, transform.forward, out hit, sensorLength) && shouldAvoid(hit))
        {
            //Debug.DrawLine(sensorStartPos, hit.point, Color.red);
            avoiding     = true;
            avoidNum    -= 0.4f;
            accelerating = false;
            breaking     = true;
        }

        Vector3 rightDir = transform.right;

        //right sensor
        sensorStartPos += sidesensorPos * rightDir;
        if (Physics.Raycast(sensorStartPos, transform.forward, out hit, sensorLength) && shouldAvoid(hit))
        {
            //Debug.DrawLine(sensorStartPos, hit.point);
            avoiding     = true;
            avoidNum    -= 1f;
            accelerating = false;
        }

        //right angle sensor
        if (Physics.Raycast(sensorStartPos, Quaternion.AngleAxis(sensorAngle, transform.up) * transform.forward, out hit, sensorLength) && shouldAvoid(hit))
        {
            //Debug.DrawLine(sensorStartPos, hit.point);
            avoiding  = true;
            avoidNum -= 0.5f;
        }

        //left sensor
        sensorStartPos += 2 * sidesensorPos * -rightDir;
        if (Physics.Raycast(sensorStartPos, transform.forward, out hit, sensorLength) && shouldAvoid(hit))
        {
            //Debug.DrawLine(sensorStartPos, hit.point);
            avoiding     = true;
            avoidNum    += 1f;
            accelerating = false;
        }

        //left angle sensor
        if (Physics.Raycast(sensorStartPos, Quaternion.AngleAxis(-sensorAngle, transform.up) * transform.forward, out hit, sensorLength) && shouldAvoid(hit))
        {
            //Debug.DrawLine(sensorStartPos, hit.point);
            avoiding  = true;
            avoidNum += 0.5f;
        }
        if (avoiding)
        {
            shipRigidbody.AddRelativeTorque(0f, avoidNum * turnSpeed, -(avoidNum * tiltSpeed));
            stableRotation     = Quaternion.Euler(xRotation, transform.eulerAngles.y, zRotation);
            transform.rotation = Quaternion.Lerp(transform.rotation, stableRotation, Time.time * stabilizerPower);
        }
    }
Esempio n. 27
0
 void Start()
 {
     for (int i = 0; i < Generate.hor; i++)
     {
         for (int j = 0; j < Generate.vert; j++)
         {
             if (j % 2 == 0)
             {
                 minihexlist[i, j] = Instantiate(minihex, new Vector3(transform.position.x + 2 * i * horCorr, transform.position.y + 0, transform.position.z + (-2 * j * vertCorr)), Quaternion.AngleAxis(90, Vector3.up)) as GameObject;
             }
             else
             {
                 minihexlist[i, j] = Instantiate(minihex, new Vector3(transform.position.x + horCorr * 2 * i + horCorr, transform.position.y + 0, transform.position.z + (-2 * j * vertCorr)), Quaternion.AngleAxis(90, Vector3.up)) as GameObject;
             }
         }
     }
 }
Esempio n. 28
0
    public override IEnumerator mainroute()
    {
        Vector3    axis;
        GameObject bb;
        int        i1 = 0, i2 = 24, i3 = 48, j = 0;
        Vector3    v = Vector3.down;

        if (Random.value > 0.5f)
        {
            j = 5;
        }
        else
        {
            j = -5;
        }
        Vector3    yOffset = Vector3.zero;
        Quaternion wOffset = Quaternion.identity;
        Vector3    insPos1 = Vector3.zero, insPos2 = Vector3.zero, insPos3 = Vector3.zero;

        while (!stop)
        {
            axis    = new Vector3(transform.position.x, 0, transform.position.z);
            yOffset = new Vector3(0, yFactor * Mathf.Cos(Mathf.Deg2Rad * i1 * j), 0);
            wOffset = Quaternion.Euler(0, wFactor * Mathf.Sin(Mathf.Deg2Rad * i1 * j), 0);
            insPos1 = wOffset * gameObject.transform.position + yOffset;

            yOffset = new Vector3(0, yFactor * Mathf.Cos(Mathf.Deg2Rad * i2 * j), 0);
            wOffset = Quaternion.Euler(0, wFactor * Mathf.Sin(Mathf.Deg2Rad * i2 * j), 0);
            insPos2 = wOffset * gameObject.transform.position + yOffset;

            yOffset = new Vector3(0, yFactor * Mathf.Cos(Mathf.Deg2Rad * i3 * j), 0);
            wOffset = Quaternion.Euler(0, wFactor * Mathf.Sin(Mathf.Deg2Rad * i3 * j), 0);
            insPos3 = wOffset * gameObject.transform.position + yOffset;



            bb = (GameObject)Instantiate(bt2[i1 % 8], insPos1, Quaternion.identity);
            bb.AddComponent("expandhelix");
            bb.GetComponent <expandhelix> ().t         = i1 * j;
            bb.GetComponent <expandhelix>().expandType = 3;

            bb = (GameObject)Instantiate(bt2[i2 % 8], insPos2, Quaternion.identity);
            bb.AddComponent("expandhelix");
            bb.GetComponent <expandhelix> ().t         = i2 * j;
            bb.GetComponent <expandhelix>().expandType = 3;

            bb = (GameObject)Instantiate(bt2[i3 % 8], insPos3, Quaternion.identity);
            bb.AddComponent("expandhelix");
            bb.GetComponent <expandhelix> ().t         = i3 * j;
            bb.GetComponent <expandhelix>().expandType = 3;

            v = Quaternion.AngleAxis(j, axis) * v;

            i1++;
            i2++;
            i3++;
            if (i1 % 2 == 0)
            {
                audio.Play();
            }
            if (i1 == 72)
            {
                i1 = 0;
            }
            if (i2 == 72)
            {
                i2 = 0;
            }
            if (i3 == 72)
            {
                i3 = 0;
            }

            yield return(new WaitForSeconds(0.3f));
        }


        halt();
    }
Esempio n. 29
0
        void Yaw(float angle)
        {
            Quaternion rot = Quaternion.AngleAxis(angle, Vector3.up);

            transform.rotation = rot * transform.rotation;
        }
    public void Setup()
    {
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

        transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
    }