// Update is called once per frame
	void Update () {
        oldStart = start;
		start = transform.position;
        finish = start + new Vector3(0, 15);
        if (isFire)
        {
            CD -= Time.deltaTime;
            if (CD <= 0)
            {
                GetComponent<LineRenderer>().enabled = true;
                GetComponent<LineRenderer>().sortingLayerName = "Bullets";
                //GetComponent<LineRenderer>().SetPosition(0, start);
                //GetComponent<LineRenderer>().SetPosition(1, finish);
                GetComponent<LineRenderer>().SetPosition(0, Vector3.zero);
                GetComponent<LineRenderer>().SetPosition(1, new Vector3(0, 15));
                if (!start.Equals(oldStart))
                {
                    GameObject newGlow = Instantiate(afterglow);
                    newGlow.GetComponent<LineRenderer>().SetPosition(0, start);
                    newGlow.GetComponent<LineRenderer>().SetPosition(1, finish);
                }
                targets = Physics2D.RaycastAll(start, Vector2.up,100,LayerMask.GetMask("Enemy"));
                if (targets!=null)
                    foreach (RaycastHit2D item in targets)
                    {
                        if (item.collider.tag == "Enemy")
                        {
                            item.collider.SendMessage("ApplyDamage", 1f + power * 0.2f);
                        }

                    }
            }
        }
        else
        {
            GetComponent<LineRenderer>().enabled = false;
            CD = MaxCD;
        }
	}
Esempio n. 2
0
        public void EqualityTest( float x1, float y1, float z1, float x2, float y2, float z2, bool expected )
        {
            Vector3 vector1 = new Vector3( x1, y1, z1 );
            Vector3 vector2 = new Vector3( x2, y2, z2 );

            Assert.AreEqual( vector1 == vector2, expected );
            Assert.AreEqual( vector1 != vector2, !expected );

            Assert.AreEqual( vector1.Equals( vector2 ), expected );
            Assert.AreEqual( vector1.Equals( (object) vector2 ), expected );
        }
Esempio n. 3
0
 public WVector3(Vector3 v)
 {
     if(v.Equals(null)) {
         throw new ArgumentNullException();
     }
     Value = v;
 }
    public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId)
    {
        Vector3 playerSpawnPos = new Vector3(0.0F, 0.0F, 0.0F);
        Vector3 spawnA = new Vector3(0.0F, 0.0F, 0.0F);
        Vector3 spawnB = new Vector3(0.0F, 0.0F, 0.0F);

        GameObject[] spawns = GameObject.FindGameObjectsWithTag("spawn");
        GameObject[] players = GameObject.FindGameObjectsWithTag("Player");

        string target = "Spawn_A";
        Quaternion rotation = Quaternion.identity;

        if (hostConnection != -1 && conn.connectionId != hostConnection) {
            target = "Spawn_B";
            rotation = Quaternion.Euler(rotation.eulerAngles + new Vector3(0.0F, 180.0F, 0.0F));
        }
        else {
            hostConnection = conn.connectionId;
        }

        foreach (GameObject spawn in spawns ) {
            if (spawn.name == "Spawn_A") spawnA = spawn.transform.position;
            else spawnB = spawn.transform.position;
        }

        if (target == "Spawn_A") playerSpawnPos = spawnA;
        if (playerSpawnPos.Equals(new Vector3(0.0F, 0.0F, 0.0F)) || target == "Spawn_B") playerSpawnPos = spawnB;

        GameObject player = (GameObject)GameObject.Instantiate(playerPrefab, playerSpawnPos, rotation);
        NetworkServer.AddPlayerForConnection(conn, player, playerControllerId);
    }
        /// <summary>
        /// Creates a rotation matrix that will aim from one point to another. The resulting
        /// matrix can be used to make objects face a certain direction.
        /// </summary>
        /// <param name="from">The source point.</param>
        /// <param name="to">The destination point.</param>
        /// <returns>The aimed matrix.</returns>
        public static Matrix CreateAimedTransform(Vector3 from, Vector3 to)
        {
            // get a normalized vector from 'from' to 'to'
            Vector3 aimVector = to - from;
            aimVector.Normalize();

            // get a vector to the left (no roll)
            Vector3 leftVector = new Vector3(-aimVector.Y, aimVector.X, 0);
            if (!leftVector.Equals(Vector3.Zero))
                leftVector.Normalize();
            else
                leftVector = Vector3.Backward;

            // get the up vector
            Vector3 upVector = Vector3.Cross(aimVector, leftVector);
            upVector.Normalize();

            // create the matrix
            Matrix transform = Matrix.Identity;
            transform.Up = aimVector;
            transform.Backward = upVector;
            transform.Left = leftVector;

            // set the translation to the from position
            transform.Translation = from;

            // return the new matrix
            return transform;
        }
Esempio n. 6
0
            public void DifferentAreNotEqual()
            {
                var v1 = new Vector3(10, 10, 10);
                var v2 = new Vector3(1, 1, 1);

                Assert.IsFalse(v1.Equals(v2), "Vector with different values should not be equal");
            }
	public void powerupGone(Vector3 pos){
		for (int i = 0; i < itemSpawnPoints.Length; i++) {
			if(pos.Equals(itemSpawnPoints[i])){
				item[i] = false;
				break;
			}
		}
	}
Esempio n. 8
0
        public UInt16 FindVert(Vector3 v)
        {
            UInt16 index = (UInt16)Geometry.Vertecies.FindIndex(delegate(Vector3 p) { return v.Equals(p); });
            if (index >= 0)
                return index;

            Geometry.Vertecies.Add(v);
            return (UInt16)(Geometry.Vertecies.Count - 1);
        }
Esempio n. 9
0
		public void ScalarDivision()
		{
			Vector3 ScalarMultiplicationArgument = new Vector3(5.0f, 4.0f, 3.0f);
			Assert.IsTrue(ScalarMultiplicationArgument / 2 == new Vector3(2.5f, 2.0f, 1.5f));
			Assert.IsTrue(2 / ScalarMultiplicationArgument == new Vector3(2.5f, 2.0f, 1.5f));

			Vector3 Point3 = new Vector3(12, 18, 24);
			Point3 /= 6;
			Assert.IsTrue(Point3.Equals(new Vector3(2, 3, 4), .01f));
		}
Esempio n. 10
0
    void FixedUpdate()
    {
        targetPosition = GetComponent<BubbleExplorer>().targetPosition;

        if (!targetPosition.Equals(lastTargetPosition))
        {
            lastTargetPosition = targetPosition;
            PathRequestManager.RequestPath(transform.position, targetPosition, OnPathFound);
           // ListPathRequestManager.RequestPath(transform.position, targetPosition, grid.unwalkable, new List<Node>(),OnPathFound);
            path = null;
        }
        else {
            if (path != null && Vector3.Distance(transform.position, targetPosition) > 0.05f)
            {
                if (Vector3.Distance(transform.position, currentWayPoint + height) < 0.05f)
                {
                    targetIndex++;
                    currentWayPoint = path[targetIndex];
                }

                if (!recheckPath())
                {
                    PathRequestManager.RequestPath(transform.position, targetPosition, OnPathFound);

                    //ListPathRequestManager.RequestPath(transform.position, targetPosition, grid.unwalkable,grid.dynamicUnwalkable, OnPathFound);
                    path = null;
                }
                else {

                    float angle = Vector3.Angle(transform.forward, (currentWayPoint) + height - transform.position);

                    bool posDir = (Vector3.Angle(transform.right, (currentWayPoint) + height - transform.position) > 90);
                    int rot = Mathf.RoundToInt(angle / rotationUnit);

                    if (rot > maxRotationSpeed)
                    {
                        rot = maxRotationSpeed;
                    }
                    Quaternion deltaRotation;
                    if (posDir)
                    {
                        deltaRotation = Quaternion.Euler(0.0f, -(rot * rotationUnit), 0.0f);
                    }
                    else {
                        deltaRotation = Quaternion.Euler(0.0f, (rot * rotationUnit), 0.0f);
                    }
                    rb.MoveRotation(rb.rotation * deltaRotation);
                    if (Mathf.Abs(angle) < rotationDirectionDifference)
                    {
                        transform.position = Vector3.MoveTowards(transform.position, currentWayPoint + height, movementSpeed * Time.deltaTime);
                    }
                }
            }
        }
    }
Esempio n. 11
0
        public JsConsole(Game1 game, Vector3 pos, Vector3 dir)
            : base()
        {
            this.game = game;
            this.pos = pos;
            minigame = game.minigame;
            instance = new MgInstance(game, minigame);
            ship = game.ship;
            this.dir = dir;
            successAtActivate = -1;

            interactRange = new CircleCollider(this.pos + dir * 16, 3);
            interestRange = new CircleCollider(this.pos + dir * 16, 20);

            model = new JsConsoleModel(this, game);
            game.modelManager.addObject(model);
            nodePos = new Vector2((int)((this.pos.X / 30) + 0.5f), (int)((this.pos.Z / 30) + 0.5f));

            destroying = false;

            cardCount = 0;
            consolePos = pos + dir * 15;
            consolePos.Y = 4.5f;

            cols = new List<OOBB>();
            cols.Add(new OOBB(consolePos + dir*1, dir, 5, 1, dir));
            cols.Add(new OOBB(consolePos + dir*-1, dir, 5, 1, -dir));
            cols.Add(new OOBB(consolePos + Vector3.Cross(dir, Vector3.Up) * -2f, dir, 2, 1, Vector3.Cross(-dir, Vector3.Up)));
            cols.Add(new OOBB(consolePos + Vector3.Cross(-dir, Vector3.Up) * -2f, dir, 2, 1, Vector3.Cross(dir, Vector3.Up)));

            cols.Add(new OOBB(pos + dir * 13, dir, 30, 1, dir));

            if(dir.Equals(Vector3.Left) || dir.Equals(Vector3.Right))
            {
                forcefield = new ForcefieldDrill(game, pos + dir * 13, 1);
            }
            else
            {
                forcefield = new ForcefieldDrill(game, pos + dir * 13, 0);
            }
            game.modelManager.addAdditive(forcefield);
        }
Esempio n. 12
0
        static bool TestOne(double Tx, double Ty, double Tz, double Rx, double Ry, double Rz, double Sx, double Sy, double Sz)
        {
            Vector3 UnitVectorY = new Vector3(0.0f, 1.0f, 0.0f);
            Vector3 v1 = new Vector3();
	        v1 = UnitVectorY;
            Matrix4X4 NormalMatrix = Matrix4X4.Identity;
            Matrix4X4 InverseMatrixFromNormalMatrix = Matrix4X4.Identity;
            Matrix4X4 InverseMatrixCalculated = Matrix4X4.Identity;

	        NormalMatrix.PrepareMatrix(Tx, Ty, Tz, Rx, Ry, Rz, Sx, Sy, Sz);
	        NormalMatrix.TransformVector(ref v1);

            InverseMatrixFromNormalMatrix.SetToInverse(NormalMatrix);
            InverseMatrixFromNormalMatrix.TransformVector(ref v1);

	        // make sure they are the same within an error range
            Assert.IsTrue(v1.Equals(UnitVectorY, .01f));

            NormalMatrix.TransformVector(ref v1);

	        InverseMatrixCalculated.PrepareInvMatrix(-Tx, -Ty, -Tz, -Rx, -Ry, -Rz, 1.0f/Sx, 1.0f/Sy, 1.0f/Sz);
            InverseMatrixCalculated.TransformVector(ref v1);

	        // make sure they are the same within an error range
            Assert.IsTrue(v1.Equals(UnitVectorY, .001f));

	        // And just a bit more checking [7/26/2001] LBB
	        // and now just check that TransformVector is always working
	        NormalMatrix.PrepareMatrix(Tx, Ty, Tz, Rx, Ry, Rz, Sx, Sy, Sz);
            NormalMatrix.TransformVector3X3(ref v1);
	        InverseMatrixCalculated.PrepareInvMatrix(-Tx, -Ty, -Tz, -Rx, -Ry, -Rz, 1.0f/Sx, 1.0f/Sy, 1.0f/Sz);
            InverseMatrixCalculated.TransformVector3X3(ref v1);
            Assert.IsTrue(v1.Equals(UnitVectorY, .001f));

	        NormalMatrix.PrepareMatrix(Tx, Ty, Tz, Rx, Ry, Rz, Sx, Sy, Sz);
            NormalMatrix.TransformVector3X3(ref v1);
            InverseMatrixCalculated.SetToInverse(NormalMatrix);
            InverseMatrixCalculated.TransformVector3X3(ref v1);
            Assert.IsTrue(v1.Equals(UnitVectorY, .001f));

	        return true;
        }
Esempio n. 13
0
		public void ScalarMultiplication()
		{
			Vector3 ScalarMultiplicationArgument = new Vector3(5.0f, 4.0f, 3.0f);
			Assert.IsTrue(ScalarMultiplicationArgument * -.5 == -new Vector3(2.5f, 2.0f, 1.5f));
			Assert.IsTrue(-.5 * ScalarMultiplicationArgument == -new Vector3(2.5f, 2.0f, 1.5f));
			Assert.IsTrue(5 * ScalarMultiplicationArgument == new Vector3(25.0f, 20.0f, 15.0f));

			Vector3 Point3 = new Vector3(2, 3, 4);
			Point3 *= 6;
			Assert.IsTrue(Point3.Equals(new Vector3(12, 18, 24), .01f));
		}
Esempio n. 14
0
	void setColor(Vector3 seb) {
		if (seb.Equals(Vector3.zero)) {
			if (getViewCount(VIS_DIST) != 0) {
				gameObject.GetComponent<Renderer>().material.color = Color.white;
			} else {
				gameObject.GetComponent<Renderer>().material.color = Color.blue;
			}
		} else {
			gameObject.GetComponent<Renderer>().material.color = Color.red;
		}
	}
Esempio n. 15
0
 public override void CmdActivate(Arguments args)
 {
     if (!isOnCooldown()) // check if we can cast it
     {
         Vector3 point = new Vector3();
         if (!point.Equals(new Vector3()))
         {
             startCooldown();
             Cmdspawnit(point);
         }
     }
 }
	public static Vector3[] OffsetPoints (this Vector3[] points, Vector3 offset)
	{
		if (offset.Equals (Vector3.zero))
			return points;
		// Make a flat clone of the original array
		var ofsPoints = Enumerable.Repeat (Vector3.zero, points.Length).ToArray ();
		Array.Copy (points, ofsPoints, points.Length);
		for (int i = 0; i < ofsPoints.Length; i++) {
			ofsPoints[i] = ofsPoints[i] + offset;
		}
		return ofsPoints;
	}
    void OnEnable()
    {
        scriptTarget = (Direction) target;

        rotationEuler = toVector3(scriptTarget.rotation);
        rotationEuler.x = (float) decimal.Round((decimal) rotationEuler.x, 2, MidpointRounding.AwayFromZero);
        rotationEuler.y = (float) decimal.Round((decimal) rotationEuler.y, 2, MidpointRounding.AwayFromZero);
        rotationEuler.z = (float) decimal.Round((decimal) rotationEuler.z, 2, MidpointRounding.AwayFromZero);

        useDefault = rotationEuler.Equals(DirectionUtil.getDefaultEulerAngles(scriptTarget.direction)) ||
            rotationEuler.magnitude == 0;
    }
 private void scaleFromPosition(Vector3 scale, Vector3 fromPos)
 {
     if(!fromPos.Equals(prevPos))
     {
         Vector3 prevParentPos = transform.position;
         transform.position = fromPos;
         Vector3 diff = transform.position - prevParentPos;
         Vector3 pos = new Vector3(diff.x/transform.localScale.x*-1, diff.y/transform.localScale.y*-1, transform.position.z);
         transform.localPosition = new Vector3(transform.localPosition.x + pos.x, transform.localPosition.y+pos.y, pos.z);
     }
     transform.localScale = scale;
     prevPos = fromPos;
 }
Esempio n. 19
0
 //
 void GeneraRotacion( Vector3 vectorAux )
 {
     if (vectorAux.Equals(Vector3.zero))
         return;
     float dot = Vector3.Dot(this.transform.up,vectorAux);
     if (dot < 0.05 && dot > -0.05)
     {
         Vector3 cross = Vector3.Cross(this.transform.up, vectorAux);
         float angulo = Vector3.Angle(this.transform.up, vectorAux);
         print(string.Format("{0} {1} {2}", dot, cross, angulo));
         this.transform.eulerAngles += new Vector3(0f, 0f, angulo * (cross.z < 0 ? -1 : 1));
     }
 }
Esempio n. 20
0
 public virtual void Draw(Vector3 vec)
 {
     if (!isPlaying) {
         root.transform.localPosition = vec;
         timer += Time.deltaTime;
         if (!vec.Equals (Vector3.zero))
             strokeUtils.addToTrail (Trail, trailHead, vec);
         trailToLine (0,trailHead);
         if (timer > trailLength)
             strokeUtils.shiftArray (Trail, trailHead);//	trail.RemoveAt (0);
         else {
             trailHead++;
             playbackHead++;
         }
     }
 }
Esempio n. 21
0
        public static Vector3 getDistanceBetweenPoint(Vector3 point1, Vector3 point2, Vector3 direction)
        {
            if (point1.Equals(point2))
            {
                return Vector3.Zero;
            }
            else
            {
                Vector3 distance = point2 - point1;
                Vector3 normalizedDistance = distance;
                normalizedDistance.Normalize();
                float dotProduct = Vector3.Dot(normalizedDistance, direction);

                return dotProduct * direction * distance.Length();
            }
        }
Esempio n. 22
0
    // Update is called once per frame
    void FixedUpdate()
    {
        rigidbody.isKinematic = false;
        Vector3 targetVelocity = new Vector3 (Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical"));

        if (targetVelocity.Equals(new Vector3(0,0,0)))
        {
            footstepSound.SetActive(false);
        } else
        {
            footstepSound.SetActive(true);
        }

        if (targetVelocity.magnitude > targetVelocity.normalized.magnitude)
        {
            targetVelocity = targetVelocity.normalized; // Prevents a faster movement when two keys are pressed
        }

        float modifiedspeed = speed;

        if (Input.GetButton ("Run")) // Running, the key must be held down
        {
            modifiedspeed *= 1.5f;
        }

        targetVelocity = transform.TransformDirection (targetVelocity);
        targetVelocity *= modifiedspeed*Time.deltaTime;

        rigidbody.MovePosition(rigidbody.position+targetVelocity); // Alternative movement
        //rigidbody.AddForce (targetVelocity, ForceMode.VelocityChange);

        if (Input.GetButton("Jump") && grounded)
        {
            rigidbody.AddForce (new Vector3(0,jumpSpeed,0),ForceMode.VelocityChange);
        }

        if (!grounded)
        {
            rigidbody.AddForce (new Vector3(0,-moregravity,0), ForceMode.VelocityChange);
        }

        grounded = false;
    }
    private void moveStick(String position)
    {
        String[] coordonees = position.Split(':');
        tmp = new Vector3(int.Parse(coordonees[2]),int.Parse(coordonees[1]),int.Parse(coordonees[0]));

        if(!tmp.Equals(newPosition)){
            oldPosition = newPosition;
            newPosition = tmp;
            Vector3 mvt = newPosition - oldPosition;
            X.Enqueue (mvt.x);
            Y.Enqueue (mvt.y);
            Z.Enqueue(mvt.z);

            if (X.Count > 5) {
                X.Dequeue ();
                Y.Dequeue ();
                Z.Dequeue ();
            }
            gameObject.transform.Translate (-mvt.x*0.0000f, -mvt.y*0.005f, -mvt.z*0.005f);
        }
    }
Esempio n. 24
0
    public override void Draw(Vector3 vec)
    {
        if (!isPlaying) {

            timer += Time.deltaTime;

            if(!vec.Equals(Vector3.zero))
                strokeUtils.addToTrail (Trail, trailHead, vec);

            trailToLine (0,trailHead);
            makeSubTrail ();

            foreach (GameObject t in subTrails) {
                Stroke s = t.GetComponent<Stroke> ();
                strokeUtils.addToTrail (s.Trail, ++s.trailHead, Trail [trailHead]);
            }

            trailHead++;

        }
    }
Esempio n. 25
0
    public override void Draw(Vector3 vec)
    {
        if (!isPlaying) {

            root.transform.localPosition = vec;
            timer += Time.deltaTime;
            if(!vec.Equals(Vector3.zero))
                strokeUtils.addToTrail (Trail, trailHead, vec);

        //				trail.Add (vec);
            trailToLine (0,trailHead);
        //			Debug.Log (timer+","+trailLength + "," + subTrails.Count);
            makeSubTrail ();
            foreach (GameObject t in subTrails) {
                Stroke s = t.GetComponent<Stroke> ();
                strokeUtils.addToTrail (s.Trail, ++s.trailHead, Trail [trailHead]);
        //				t.GetComponent<Stroke> ().trail.Add (trail[trail.Count-1]);
            }
            trailHead++;
        //			Debug.Log (trailHead);
        //			if (timer > trailLength) {
        //				timer = 0;
        ////				Debug.Log (timer+" , "+trailLength + " , " + subTrails.Count);
        //				subTrails.Add (Instantiate (bGlobals.strokes[0]));
        //				subTrails[subTrails.Count-1].GetComponent<Stroke>().trail = trail;
        //				subTrails [subTrails.Count - 1].GetComponent<Stroke> ().playButton ();
        //
        //			}
        //			foreach (GameObject t in subTrails) {
        ////				subTrails [subTrails.Count - 1].GetComponent<Stroke> ().
        //				subTrails [subTrails.Count - 1].GetComponent<Stroke> ().trail.Add (vec);
        //				subTrails [subTrails.Count - 1].GetComponent<Stroke> ().playBack ();
        //			}
        }
        //		foreach (GameObject s in subTrails) {
        //			s.GetComponent<Stroke> ().Draw ();
        //		}
    }
Esempio n. 26
0
 // Update is called once per frame
 void Update()
 {
     if (!stopped) {
                     if (!inTransit) {
                             inTransit = true;
                             v = pvm.checkSandPosition (transform.position.x, transform.position.y, transform.position.z);
                             if (v.Equals(transform.position)) {
                                     stopped = true;
                                     if(pvm.addBlock(transform.position.x - 0.5f,transform.position.y + 0.5f,3)){
                                         Debug.Log ("added");
                                         Destroy(gameObject);
                                     }
                                     //couldn't add, better move up
                                     v = transform.position + Vector3.up;
                                     stopped = false;
                             }
                     } else {
                             transform.position = Vector3.Lerp (transform.position, v, speed * Time.deltaTime);	//lerp to position
                             if(Vector3.Distance(transform.position,v) <= 0.2f){
                                 inTransit = false;
                             }
                     }
             }
 }
Esempio n. 27
0
 public bool Equals(Transform other)
 {
     return(position.Equals(other.position) &&
            rotation.Equals(other.rotation) &&
            scale.Equals(other.scale));
 }
 public bool Equals(Circle3 other)
 {
     return(center.Equals(other.center) && normal.Equals(other.normal) && radius.Equals(other.radius));
 }
Esempio n. 29
0
        private void HoverCamera()
        {
            if (!tiltAngle.Equals(currentTiltAngle) || !panAngle.Equals(currentPanAngle) || !target.Equals(pos))
            {
                if (wrapPanAngle)
                {
                    if (panAngle < 0)
                    {
                        currentPanAngle += panAngle % 360 + 360 - panAngle;
                        panAngle         = panAngle % 360 + 360;
                    }
                    else
                    {
                        currentPanAngle += panAngle % 360 - panAngle;
                        panAngle         = panAngle % 360;
                    }

                    while (panAngle - currentPanAngle < -180)
                    {
                        currentPanAngle -= 360;
                    }

                    while (panAngle - currentPanAngle > 180)
                    {
                        currentPanAngle += 360;
                    }
                }

                if (interpolate)
                {
                    currentTiltAngle += (tiltAngle - currentTiltAngle) / (steps + 1);
                    currentPanAngle  += (panAngle - currentPanAngle) / (steps + 1);
                }
                else
                {
                    currentPanAngle  = panAngle;
                    currentTiltAngle = tiltAngle;
                }

                //snap coords if angle differences are close
                if ((Mathf.Abs(tiltAngle - currentTiltAngle) < 0.01) && (Mathf.Abs(panAngle - currentPanAngle) < 0.01))
                {
                    currentTiltAngle = tiltAngle;
                    currentPanAngle  = panAngle;
                }

                if (MainCamera is null)
                {
                    return;
                }
                pos.x = target.x + distance * Mathf.Sin(currentPanAngle * Mathf.Deg2Rad) * Mathf.Cos(currentTiltAngle * Mathf.Deg2Rad);
                pos.z = target.z + distance * Mathf.Cos(currentPanAngle * Mathf.Deg2Rad) * Mathf.Cos(currentTiltAngle * Mathf.Deg2Rad);
                pos.y = target.y + distance * Mathf.Sin(currentTiltAngle * Mathf.Deg2Rad) * yFactor;
                MainCamera.transform.position = pos;
                MainCamera.transform.LookAt(target);
            }
        }
Esempio n. 30
0
	// Update is called once per frame
	void Update () {
		if (Input.GetKeyDown (KeyCode.Q))
			testKey = true;
		if (Input.GetKey (KeyCode.Escape)) {
			file.Close ();
			Application.Quit();
		}

		vCur = transform.rotation * Vector3.forward;
		//file.WriteLine("cur dis:\t" + Vector3.Distance (vLast, vCur));
		vLast = vCur;
		if(tc.isReadyToMove){
			// move according to invisible tracked objects
			if(!lastRefPosition.Equals(new Vector3(0,0,0))){
				drawRays();			// test rotation
				// move as reference move
				if (testKey) {
					// do it every 10 frames
					++count;
					if (count != debugCount) {
						return;
					}
					count = 0;
					testKey = true;

					vCur = transform.rotation * Vector3.forward;
					print ("update:\tvCur:\t" + vCur.ToString ("F4") );
					print ("update:\tangle:\t" + Vector3.Angle (vLast, vCur));
					// write to the file
					//file.WriteLine("cur angle:\t" + Vector3.Angle (vLast, vCur));
					//file.WriteLine("cur dis:\t" + Vector3.Distance (vLast, vCur));
					vLast = vCur;

					switch (step) {
					case 0:
						if (isCloseEnough ())
							step = 0;
						else {
							if (turnRound ()) {
								++step;
								// for test
								//step = 0;
							}
						}
						break;
					case 1:
						if (goStraight ()) {
							++step;
						} else
							step = 0;
						break;
					case 2:
						if (isCloseEnough ()) {
							// do not need to turn to the right face
							step = 0;
						} 
						break;
					case 3:
						turnBack ();
						if(isCloseEnough())
							// do not need to turn to the right face
							step = 0;
						break;
					case 4:
						if (turnFace ()) {
							step = 0;
						}
						break;
					default:
						break;
					}
				}
			}
			//testKey = false;
			lastRefPosition = referenceObj.transform.position;
			lastRefRotation = referenceObj.transform.rotation;
			lastPosition = transform.position;
			lastRotation = transform.rotation;
			//print ("pos:\t" + transform.position);
			//testKey = false;
		}
	}
Esempio n. 31
0
 /// <summary>Indicates whether the current object is equal to another object of the same type.</summary>
 /// <param name="other">An object to compare with this object.</param>
 /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
 public bool Equals(VertexPositionNormalTexture other)
 {
     return(Position.Equals(other.Position) && Normal.Equals(other.Normal) && TextureCoordinate.Equals(other.TextureCoordinate));
 }
Esempio n. 32
0
        /// <inheritdoc />
        public unsafe override int BuildVertexBuffer(ParticleVertexBuilder vtxBuilder, Vector3 invViewX, Vector3 invViewY,
                                                     ref Vector3 spaceTranslation, ref Quaternion spaceRotation, float spaceScale, ParticleSorter sorter)
        {
            // Update the curve samplers if required
            base.BuildVertexBuffer(vtxBuilder, invViewX, invViewY, ref spaceTranslation, ref spaceRotation, spaceScale, sorter);

            SamplerRotation?.UpdateChanges();



            // Get all the required particle fields
            var positionField = sorter.GetField(ParticleFields.Position);

            if (!positionField.IsValid())
            {
                return(0);
            }
            var lifeField  = sorter.GetField(ParticleFields.Life);
            var sizeField  = sorter.GetField(ParticleFields.Size);
            var angleField = sorter.GetField(ParticleFields.Angle);
            var hasAngle   = angleField.IsValid() || (SamplerRotation != null);


            // Check if the draw space is identity - in this case we don't need to transform the position, scale and rotation vectors
            var trsIdentity = (spaceScale == 1f);

            trsIdentity = trsIdentity && (spaceTranslation.Equals(new Vector3(0, 0, 0)));
            trsIdentity = trsIdentity && (spaceRotation.Equals(new Quaternion(0, 0, 0, 1)));


            var renderedParticles = 0;

            var posAttribute = vtxBuilder.GetAccessor(VertexAttributes.Position);
            var texAttribute = vtxBuilder.GetAccessor(vtxBuilder.DefaultTexCoords);

            foreach (var particle in sorter)
            {
                var centralPos = GetParticlePosition(particle, positionField, lifeField);

                var particleSize = GetParticleSize(particle, sizeField, lifeField);

                if (!trsIdentity)
                {
                    spaceRotation.Rotate(ref centralPos);
                    centralPos    = centralPos * spaceScale + spaceTranslation;
                    particleSize *= spaceScale;
                }

                // Use half size to make a Size = 1 result in a Billboard of 1m x 1m
                var unitX = invViewX * (particleSize * 0.5f);
                var unitY = invViewY * (particleSize * 0.5f);

                // Particle rotation. Positive value means clockwise rotation.
                if (hasAngle)
                {
                    var rotationAngle = GetParticleRotation(particle, angleField, lifeField);

                    var cosA  = (float)Math.Cos(rotationAngle);
                    var sinA  = (float)Math.Sin(rotationAngle);
                    var tempX = unitX * cosA - unitY * sinA;
                    unitY = unitY * cosA + unitX * sinA;
                    unitX = tempX;
                }


                var particlePos = centralPos - unitX + unitY;
                var uvCoord     = new Vector2(0, 0);
                // 0f 0f
                vtxBuilder.SetAttribute(posAttribute, (IntPtr)(&particlePos));
                vtxBuilder.SetAttribute(texAttribute, (IntPtr)(&uvCoord));
                vtxBuilder.NextVertex();


                // 1f 0f
                particlePos += unitX * 2;
                uvCoord.X    = 1;
                vtxBuilder.SetAttribute(posAttribute, (IntPtr)(&particlePos));
                vtxBuilder.SetAttribute(texAttribute, (IntPtr)(&uvCoord));
                vtxBuilder.NextVertex();


                // 1f 1f
                particlePos -= unitY * 2;
                uvCoord.Y    = 1;
                vtxBuilder.SetAttribute(posAttribute, (IntPtr)(&particlePos));
                vtxBuilder.SetAttribute(texAttribute, (IntPtr)(&uvCoord));
                vtxBuilder.NextVertex();


                // 0f 1f
                particlePos -= unitX * 2;
                uvCoord.X    = 0;
                vtxBuilder.SetAttribute(posAttribute, (IntPtr)(&particlePos));
                vtxBuilder.SetAttribute(texAttribute, (IntPtr)(&uvCoord));
                vtxBuilder.NextVertex();

                renderedParticles++;
            }

            var vtxPerShape = 4 * QuadsPerParticle;

            return(renderedParticles * vtxPerShape);
        }
Esempio n. 33
0
    void Update()
    {
        // membatalkan proses penggambaran saat proses panning/zooming
        if (Input.touchCount >= 2)
        {
            // membersihkan tampilan temporary
            ClearColor(ref this.temporaryTexture);
            this.temporaryTexture.Apply();

            // reset garis poligon yang sedang dibuat
            this.lineCount = 0;

            // reset bentuk yang sedang digambar
            this.currentDrawnShape = null;
            return;
        }


        RaycastHit hit;

        if (!Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit))
        {
            return;
        }

        Renderer     rend         = hit.transform.GetComponent <Renderer>();
        MeshCollider meshCollider = hit.collider as MeshCollider;

        if (rend == null || rend.sharedMaterial == null || rend.sharedMaterial.mainTexture == null || meshCollider == null)
        {
            return;
        }

        // jangan proses jika posisi mouse masih sama dengan posisi terakhir
        if (Vector3.Equals(hit.textureCoord, lastPixelPosition))
        {
            return;
        }

        Vector2 pixelUV = hit.textureCoord;

        Texture2D tex = rend.material.mainTexture as Texture2D;

        pixelUV.x *= tex.width;
        pixelUV.y *= tex.height;


        // Menerima input mouse pertama ditekan
        if (Input.GetMouseButtonDown(0))
        {
            startDownPos = pixelUV;

            switch (this.CurrentDrawingMode)
            {
            case DrawingMode.Line:
                currentDrawnShape      = new ShapeModel();
                currentDrawnShape.Mode = DrawingMode.Line;
                break;

            case DrawingMode.Triangle:
                // posisi awal menekan mouse
                if (lineCount == 0)
                {
                    currentDrawnShape      = new ShapeModel();
                    currentDrawnShape.Mode = DrawingMode.Triangle;

                    startTrianglePos = startDownPos;

                    // tambahkan data titik awal
                    currentDrawnShape.Vertices.Add(pixelUV);
                }
                break;

            case DrawingMode.Rectangle:
                currentDrawnShape      = new ShapeModel();
                currentDrawnShape.Mode = DrawingMode.Rectangle;

                // data titik awal gambar segi empat
                currentDrawnShape.Vertices.Add(new Vector2(startDownPos.x, startDownPos.y));
                currentDrawnShape.Vertices.Add(new Vector2(pixelUV.x, startDownPos.y));
                currentDrawnShape.Vertices.Add(new Vector2(pixelUV.x, pixelUV.y));
                currentDrawnShape.Vertices.Add(new Vector2(startDownPos.x, pixelUV.y));

                break;
            }
        }

        // Menerima input mouse sedang ditekan
        if (Input.GetMouseButton(0))
        {
            switch (this.CurrentDrawingMode)
            {
            case DrawingMode.Line:
                tempTargetRender.gameObject.SetActive(true);

                if (hit.transform == tempTargetRender.transform)
                {
                    ClearColor(ref temporaryTexture);
                    DrawBresenhamLine(ref temporaryTexture, (int)startDownPos.x, (int)startDownPos.y, (int)pixelUV.x, (int)pixelUV.y);
                }
                break;

            case DrawingMode.Triangle:
                tempTargetRender.gameObject.SetActive(true);

                if (lineCount == 0 && (startDownPos.x != pixelUV.x && startDownPos.y != pixelUV.y))
                {
                    lastMouseUpPos = startDownPos;
                    lineCount      = 1;
                    // tambahkan data titik baru
                    currentDrawnShape.Vertices.Add(pixelUV);
                }

                if (currentDrawnShape.Vertices.Count > 0)
                {
                    currentDrawnShape.Vertices[currentDrawnShape.Vertices.Count - 1] = pixelUV;
                }

                break;

            case DrawingMode.Rectangle:
                tempTargetRender.gameObject.SetActive(true);

                break;
            }
        }


        // Menerima input ketika mouse diangkat
        if (Input.GetMouseButtonUp(0) && currentDrawnShape != null)
        {
            switch (this.CurrentDrawingMode)
            {
            // menggambar garis
            case DrawingMode.Line:

                // menambahkan titik awal
                currentDrawnShape.Vertices.Add(startDownPos);
                // menambahkan titik akhir
                currentDrawnShape.Vertices.Add(pixelUV);
                // menyimpan data gambar
                ShapeModels.Add(currentDrawnShape);

                // reset data yang sedang digambar
                currentDrawnShape = null;


                break;

            // menggambar segitiga
            case DrawingMode.Triangle:

                // menghitung jumlah garis yang sudah digambar
                // indeks titik 0, 1, dan 2
                if (lineCount < 2)
                {
                    if (lineCount == 0 && (startDownPos.x != pixelUV.x && startDownPos.y != pixelUV.y))
                    {
                        lineCount = 1;
                    }
                    else
                    {
                        lineCount++;

                        // tambahkan data titik baru
                        currentDrawnShape.Vertices.Add(pixelUV);
                    }
                }
                else
                {
                    // tambahkan data gambar
                    ShapeModels.Add(currentDrawnShape);


                    // reset indeks garis
                    lineCount = 0;

                    // reset data yang sedang digambar
                    currentDrawnShape = null;
                }

                break;

            // menggambar segi empat
            case DrawingMode.Rectangle:

                currentDrawnShape.Vertices[0] = new Vector2(startDownPos.x, startDownPos.y);
                currentDrawnShape.Vertices[1] = new Vector2(pixelUV.x, startDownPos.y);
                currentDrawnShape.Vertices[2] = new Vector2(pixelUV.x, pixelUV.y);
                currentDrawnShape.Vertices[3] = new Vector2(startDownPos.x, pixelUV.y);

                // tambahkan data gambar persegi
                ShapeModels.Add(currentDrawnShape);

                // reset data yang sedang digambar
                currentDrawnShape = null;

                break;
            }
            lastMouseUpPos = pixelUV;

            ClearColor(ref temporaryTexture);

            RenderShapes(ref targetTexture);
        }

        // Preview update
        if (currentDrawnShape != null && currentDrawnShape.Vertices.Count > 0)
        {
            Vector2 vertex1, vertex2;

            switch (this.CurrentDrawingMode)
            {
            case DrawingMode.Triangle:
                // titik yang sedang digerakkan
                currentDrawnShape.Vertices[currentDrawnShape.Vertices.Count - 1] = pixelUV;
                break;

            case DrawingMode.Rectangle:

                currentDrawnShape.Vertices[0] = new Vector2(startDownPos.x, startDownPos.y);
                currentDrawnShape.Vertices[1] = new Vector2(pixelUV.x, startDownPos.y);
                currentDrawnShape.Vertices[2] = new Vector2(pixelUV.x, pixelUV.y);
                currentDrawnShape.Vertices[3] = new Vector2(startDownPos.x, pixelUV.y);

                break;
            }

            // proses menggambar garis-garis preview
            ClearColor(ref temporaryTexture);
            for (int itVertex = 0; itVertex < currentDrawnShape.Vertices.Count - 1; itVertex++)
            {
                if (itVertex < currentDrawnShape.Vertices.Count - 1)
                {
                    vertex1 = currentDrawnShape.Vertices[itVertex];
                    vertex2 = currentDrawnShape.Vertices[itVertex + 1];

                    int x1 = (int)vertex1.x;
                    int y1 = (int)vertex1.y;
                    int x2 = (int)vertex2.x;
                    int y2 = (int)vertex2.y;

                    // garis penghubung
                    DrawBresenhamLine(ref temporaryTexture, x1, y1, x2, y2);
                }
            }

            switch (this.CurrentDrawingMode)
            {
            case DrawingMode.Rectangle:
                // garis penghubung terakhir untuk gambar segi empat
                vertex1 = currentDrawnShape.Vertices[currentDrawnShape.Vertices.Count - 1];
                vertex2 = currentDrawnShape.Vertices[0];
                int x1 = (int)vertex1.x;
                int y1 = (int)vertex1.y;
                int x2 = (int)vertex2.x;
                int y2 = (int)vertex2.y;
                DrawBresenhamLine(ref temporaryTexture, x1, y1, x2, y2);
                break;
            }
        }
        lastPixelPosition = hit.textureCoord;
        tex.Apply();
    }
Esempio n. 34
0
 public bool IsNull() => pos.Equals(Vector3.zero) && rot.Equals(Quaternion.identity);
        /// <summary>
        /// Spawns a new Instance in the Gameworld and registers itself to the Static Database
        /// </summary>
        /// <param name="editing"></param>
        /// <param name="bPreview"></param>
        internal void SpawnObject(Boolean editing = false, Boolean bPreview = false)
        {
            // mangle Squads statics
            if (model.isSquad)
            {
                InstanceUtil.MangleSquadStatic(this);
            }

            // Objects spawned at runtime should be active, ones spawned at loading not
            InstanceUtil.SetActiveRecursively(this, editing);

            Transform[]       gameObjectList = gameObject.GetComponentsInChildren <Transform>();
            List <GameObject> rendererList   = (from t in gameObjectList where t.gameObject.GetComponent <Renderer>() != null select t.gameObject).ToList();

            InstanceUtil.SetLayerRecursively(this, 15);

            if (bPreview && editing)
            {
                this.ToggleAllColliders(false);
            }


            this.preview = bPreview;

            if (editing)
            {
                KerbalKonstructs.instance.selectObject(this, true, true, bPreview);
            }

            InstanceUtil.CreateGroupCenterIfMissing(this);

            groupCenter = StaticDatabase.allCenters[groupCenterName];

            if (RelativePosition.Equals(Vector3.zero))
            {
                Log.Normal("LegacySpawnInstance called for " + configPath);
                LegacySpawnInstance();
                gameObject.transform.parent = groupCenter.gameObject.transform;
                pqsCity.enabled             = false;
                pqsCity.sphere = null;
                pqsCity        = null;

                RelativePosition = gameObject.transform.localPosition;
                Orientation      = gameObject.transform.localEulerAngles;
            }
            else
            {
                gameObject.transform.position         = groupCenter.gameObject.transform.position;
                gameObject.transform.parent           = groupCenter.gameObject.transform;
                gameObject.transform.localPosition    = RelativePosition;
                gameObject.transform.localEulerAngles = Orientation;
            }

            //Scaling
            origScale = gameObject.transform.localScale;             // save the original scale for later use
            gameObject.transform.localScale *= ModelScale;

            RefLatitude    = (float)CelestialBody.GetLatitudeAndLongitude(gameObject.transform.position).x;
            RefLongitude   = (float)(CelestialBody.GetLatitudeAndLongitude(gameObject.transform.position).y);
            RadialPosition = radialPosition;

            foreach (StaticModule module in model.modules)
            {
                Type         moduleType = AssemblyLoader.loadedAssemblies.SelectMany(asm => asm.assembly.GetTypes()).FirstOrDefault(t => t.Namespace == module.moduleNamespace && t.Name == module.moduleClassname);
                StaticModule mod        = gameObject.AddComponent(moduleType) as StaticModule;

                if (mod != null)
                {
                    mod.staticInstance = this;
                    foreach (string fieldName in module.moduleFields.Keys)
                    {
                        FieldInfo field = mod.GetType().GetField(fieldName);
                        if (field != null)
                        {
                            field.SetValue(mod, Convert.ChangeType(module.moduleFields[fieldName], field.FieldType));
                        }
                        else
                        {
                            Log.UserWarning("Field " + fieldName + " does not exist in " + module.moduleClassname);
                        }
                    }
                }
                else
                {
                    Log.UserError("Module " + module.moduleClassname + " could not be loaded in " + gameObject.name);
                }
            }

            foreach (GameObject gorenderer in rendererList)
            {
                gorenderer.GetComponent <Renderer>().enabled = true;
            }

            StaticDatabase.AddStatic(this);

            // Add them to the bodys objectlist, so they show up as anomalies
            // After we got a new Name from StaticDatabase.AddStatic()
            if (isScanable)
            {
                Log.Normal("Added " + gameObject.name + " to scanable Objects");
                var pqsObjectList = CelestialBody.pqsSurfaceObjects.ToList();
                if (!pqsObjectList.Contains((PQSSurfaceObject)groupCenter.pqsCity))
                {
                    pqsObjectList.Add(groupCenter.pqsCity as PQSSurfaceObject);
                }
                CelestialBody.pqsSurfaceObjects = pqsObjectList.ToArray();
            }
        }
Esempio n. 36
0
 /// <summary>Returns a value indicating whether this <see cref="BoundingSphere"/> equals another <see cref="BoundingSphere"/>.</summary>
 /// <param name="other">A <see cref="BoundingSphere"/>.</param>
 /// <returns>Returns true if the bounding spheres are equal, otherwise returns false.</returns>
 public bool Equals(BoundingSphere other)
 {
     return((Radius == other.Radius) && Center.Equals(ref other.Center));
 }
Esempio n. 37
0
    void Update()
    {
        if (petrol > startingPetrol && !boss)
        {
            petrol = startingPetrol;
        }
        if (petrol < 0)
        {
            petrol = 0;
        }
        if (petrol > 0)
        {
            fuelGuage.transform.GetChild(0).GetComponent <Image>().color = Color.white;
        }
        if (petrol == 0)
        {
            fuelGuage.transform.GetChild(0).GetComponent <Image>().color = new Color(0.4f, 0.4f, 0.4f);
        }

        //CHEAT
        if (Input.GetKeyDown(KeyCode.F5))
        {
            AddFuel();
        }

        if (isMoving && time > 0)
        {
            time -= Time.deltaTime;
        }
        if (isMoving && time < 0)
        {
            petrol--;
            fuelGuage.value = petrol;
            time            = 0.5f;
        }

        if (Input.GetButtonDown("Submit") && allowed2 && (!vanFull || GetPlayer().Equals(GameManager.playerTwo)))
        {
            startDriving        = !startDriving;
            endStartDrivingBool = false;
            indicatorText2.gameObject.GetComponent <TextMeshPro>().enabled = false;
            SetPlayer(GameManager.playerTwo);
        }
        if (Input.GetKeyDown(KeyCode.F) && allowed1 && (!vanFull || GetPlayer().Equals(GameManager.playerOne)))
        {
            startDriving        = !startDriving;
            endStartDrivingBool = false;
            indicatorText1.gameObject.GetComponent <TextMeshPro>().enabled = false;
            SetPlayer(GameManager.playerOne);
        }

        {
            if (startDriving && !endStartDrivingBool)
            {
                driving = true;
                DriveStart(GetPlayer());
                endStartDrivingBool = true;
            }
            if (!startDriving && !endStartDrivingBool)
            {
                driving = false;
                DriveEnd(GetPlayer());
                endStartDrivingBool = true;
            }
        }

        if (driving && petrol > 0)
        {
            Vector3 movement = GameManager.GetMovementVectorForControlScheme(playerInVan.GetComponent <PlayerController>().controlScheme, 1.0f / Time.deltaTime);
            if (movement.Equals(Vector3.zero))
            {
                isMoving = false;
            }
            else
            {
                isMoving = true;
            }
            van.transform.Rotate(Vector3.up * movement.x * steering);                            //was h
            van.transform.position += transform.up * movement.z * acceleration * Time.deltaTime; //was v
        }
    }
Esempio n. 38
0
 public bool IsFacingDirection(Vector3 direction)
 {
     return(direction.Equals(m_currentDirection));
 }
Esempio n. 39
0
        protected virtual void FixedUpdate()
        {
            HandleFalling();
            // If Move In Place is currently engaged.
            if (active && !currentlyFalling)
            {
                // Initialize the list average.
                float listAverage = 0;

                foreach (Transform trackedObj in trackedObjects)
                {
                    // Get the amount of Y movement that's occured since the last update.
                    float deltaYPostion = Mathf.Abs(previousYPositions[trackedObj] - trackedObj.transform.localPosition.y);

                    // Convenience code.
                    List <float> trackedObjList = movementList[trackedObj];

                    // Cap off the speed.
                    if (deltaYPostion > sensitivity)
                    {
                        trackedObjList.Add(sensitivity);
                    }
                    else
                    {
                        trackedObjList.Add(deltaYPostion);
                    }

                    // Keep our tracking list at m_averagePeriod number of elements.
                    if (trackedObjList.Count > averagePeriod)
                    {
                        trackedObjList.RemoveAt(0);
                    }

                    // Average out the current tracker's list.
                    float sum = 0;
                    foreach (float diffrences in trackedObjList)
                    {
                        sum += diffrences;
                    }
                    float avg = sum / averagePeriod;

                    // Add the average to the the list average.
                    listAverage += avg;
                }

                float speed = ((speedScale * 350) * (listAverage / trackedObjects.Count));

                if (speed > maxSpeed && maxSpeed >= 0)
                {
                    speed = maxSpeed;
                }

                direction = Vector3.zero;

                // If we're doing a decoupling method...
                if (directionMethod == DirectionalMethod.SmartDecoupling || directionMethod == DirectionalMethod.DumbDecoupling)
                {
                    // If we haven't set an inital gaze yet, set it now.
                    // If we're doing dumb decoupling, this is what we'll be sticking with.
                    if (initalGaze.Equals(Vector3.zero))
                    {
                        initalGaze = new Vector3(headset.forward.x, 0, headset.forward.z);
                    }

                    // If we're doing smart decoupling, check to see if we want to reset our distance.
                    if (directionMethod == DirectionalMethod.SmartDecoupling)
                    {
                        bool  closeEnough = true;
                        float curXDir     = headset.rotation.eulerAngles.y;
                        if (curXDir <= smartDecoupleThreshold)
                        {
                            curXDir += 360;
                        }

                        closeEnough = closeEnough && (Mathf.Abs(curXDir - controllerLeftHand.transform.rotation.eulerAngles.y) <= smartDecoupleThreshold);
                        closeEnough = closeEnough && (Mathf.Abs(curXDir - controllerRightHand.transform.rotation.eulerAngles.y) <= smartDecoupleThreshold);

                        // If the controllers and the headset are pointing the same direction (within the threshold) reset the direction the player's moving.
                        if (closeEnough)
                        {
                            initalGaze = new Vector3(headset.forward.x, 0, headset.forward.z);
                        }
                    }
                    direction = initalGaze;
                }
                // if we're doing controller rotation movement
                else if (directionMethod.Equals(DirectionalMethod.ControllerRotation))
                {
                    direction = DetermineAverageControllerRotation() * Vector3.forward;
                }
                // Otherwise if we're just doing Gaze movement, always set the direction to where we're looking.
                else if (directionMethod.Equals(DirectionalMethod.Gaze))
                {
                    direction = (new Vector3(headset.forward.x, 0, headset.forward.z));
                }

                // Update our current speed.
                currentSpeed = speed;
            }
            else if (currentSpeed > 0f)
            {
                currentSpeed -= (currentlyFalling ? fallingDeceleration : deceleration);
            }
            else
            {
                currentSpeed = 0f;
                direction    = Vector3.zero;
            }

            foreach (Transform trackedObj in trackedObjects)
            {
                // Get delta postions and rotations
                previousYPositions[trackedObj] = trackedObj.transform.localPosition.y;
            }

            Vector3 movement = (direction * currentSpeed) * Time.fixedDeltaTime;

            if (playArea)
            {
                playArea.position = new Vector3(movement.x + playArea.position.x, playArea.position.y, movement.z + playArea.position.z);
            }
        }
        //-------------------------------------------------
        // Computes the angle to rotate the game object based on the change in the transform
        //-------------------------------------------------
        private void ComputeAngle(Hand hand)
        {
            Vector3 toHandProjected = ComputeToTransformProjected(hand.hoverSphereTransform);

            if (!toHandProjected.Equals(lastHandProjected))
            {
                float absAngleDelta = Vector3.Angle(lastHandProjected, toHandProjected);

                if (absAngleDelta > 0.0f)
                {
                    if (frozen)
                    {
                        float frozenSqDist = (hand.hoverSphereTransform.position - frozenHandWorldPos).sqrMagnitude;
                        if (frozenSqDist > frozenSqDistanceMinMaxThreshold.x)
                        {
                            outAngle = frozenAngle + Random.Range(-1.0f, 1.0f);

                            float magnitude = Util.RemapNumberClamped(frozenSqDist, frozenSqDistanceMinMaxThreshold.x, frozenSqDistanceMinMaxThreshold.y, 0.0f, 1.0f);
                            if (magnitude > 0)
                            {
                                StartCoroutine(HapticPulses(hand.controller, magnitude, 10));
                            }
                            else
                            {
                                StartCoroutine(HapticPulses(hand.controller, 0.5f, 10));
                            }

                            if (frozenSqDist >= frozenSqDistanceMinMaxThreshold.y)
                            {
                                onFrozenDistanceThreshold.Invoke();
                            }
                        }
                    }
                    else
                    {
                        Vector3 cross = Vector3.Cross(lastHandProjected, toHandProjected).normalized;
                        float   dot   = Vector3.Dot(worldPlaneNormal, cross);

                        float signedAngleDelta = absAngleDelta;

                        if (dot < 0.0f)
                        {
                            signedAngleDelta = -signedAngleDelta;
                        }

                        if (limited)
                        {
                            float angleTmp = Mathf.Clamp(outAngle + signedAngleDelta, minAngle, maxAngle);

                            if (outAngle == minAngle)
                            {
                                if (angleTmp > minAngle && absAngleDelta < minMaxAngularThreshold)
                                {
                                    outAngle          = angleTmp;
                                    lastHandProjected = toHandProjected;
                                }
                            }
                            else if (outAngle == maxAngle)
                            {
                                if (angleTmp < maxAngle && absAngleDelta < minMaxAngularThreshold)
                                {
                                    outAngle          = angleTmp;
                                    lastHandProjected = toHandProjected;
                                }
                            }
                            else if (angleTmp == minAngle)
                            {
                                outAngle          = angleTmp;
                                lastHandProjected = toHandProjected;
                                onMinAngle.Invoke();
                                if (freezeOnMin)
                                {
                                    Freeze(hand);
                                }
                            }
                            else if (angleTmp == maxAngle)
                            {
                                outAngle          = angleTmp;
                                lastHandProjected = toHandProjected;
                                onMaxAngle.Invoke();
                                if (freezeOnMax)
                                {
                                    Freeze(hand);
                                }
                            }
                            else
                            {
                                outAngle          = angleTmp;
                                lastHandProjected = toHandProjected;
                            }
                        }
                        else
                        {
                            outAngle         += signedAngleDelta;
                            lastHandProjected = toHandProjected;
                        }
                    }
                }
            }
        }
Esempio n. 41
0
 public bool IsValid()
 {
     return(!playerPosition.Equals(Vector3.zero));
 }
Esempio n. 42
0
 public CfgEncoder Add_IfNotOne(string tag, Vector3 v3) => v3.Equals(Vector3.one) ? this : Add(tag, v3.Encode());
Esempio n. 43
0
    //static int m_touch_num = 0;

    static public void Update()
    {
        bool lastUp = false;

        if (HasTouchDown(0))
        {
            lastUp = true;

            m_deltaPos = Vector3.zero;

            m_downing0 = true;
            m_moving   = false;

            m_slideDist = 0.0f;

            m_downPos = GeTouchPos();

            if (Time.time - m_lastDownTime < 0.5f)
            {
                m_double = true;
            }
            else
            {
                m_double = false;
            }

            m_lastDownTime = Time.time;
        }

        if (HasTouchUp(0))
        {
            m_downing0 = false;
            m_moving   = false;
            m_deltaPos = Vector3.zero;
        }

        if (Application.isEditor)
        {
            if (HasTouchDown(1))
            {
                //Log.Error("btn 2 down");
                m_downing1 = true;
            }

            if (HasTouchUp(1))
            {
                m_downing1 = false;
            }
        }

        if (m_downing0)
        {
            Vector3 pos = GeTouchPos();
            if (lastUp == false && pos.Equals(m_mousePos) == false)
            {
                m_deltaPos = pos - m_mousePos;
                m_moving   = true;
            }
            else
            {
                m_deltaPos = Vector3.zero;
                m_moving   = false;
            }

            m_mousePos = pos;
        }
    }
        private static List <T> InstantiateAgents(Transform agentParent, ICollection <Transform> agentsGoals, GameObject agentPrefab, int numberOfAgents, GameObject environmentModel, int tries = DEFAULT_TRIES, float distance = DEFAULT_DISTANCE)
        {
            if (agentsGoals.Count <= 0)
            {
                var goal = new GameObject {
                    transform = { position = new Vector3(15f, 0f, 0f) }
                };
                agentsGoals.Add(goal.transform); //For debug purposes, just add a valid goal
            }


            List <T> agents = new List <T>(numberOfAgents);
            Bounds   bounds = environmentModel.CalculateRendererBounds();

            for (int i = 0; i < numberOfAgents; i++)
            {
                GameObject   agentGameObject = Object.Instantiate(agentPrefab, agentParent);
                NavMeshAgent?navAgent        = agentGameObject.GetComponent <NavMeshAgent>();

                if (!agentGameObject.TryGetComponent(out T agent))
                {
                    agent = agentGameObject.AddComponent <T>();
                }

                if (agentGameObject.GetComponentDependants <NavMeshAgent>().Count == 0)
                {
                    navAgent.DestroyApplicationSafe();
                }

                bool failed = true;
                for (int j = 0; j < tries; j++)
                {
                    Vector3 position = GetRandomPointOnNavMesh(bounds, environmentModel.transform, distance);

                    if (position.Equals(Vector3.positiveInfinity))
                    {
                        continue;
                    }

                    if (navAgent != null)
                    {
                        navAgent.Warp(position);                   //TODO consider doing this check in agent
                    }
                    else
                    {
                        agentGameObject.transform.position = position;
                    }

                    if (!SetGoal(agent, position, agentsGoals))
                    {
                        continue;
                    }

                    failed = false;
                    break;
                }

                if (failed)
                {
                    agentGameObject.DestroyApplicationSafe();

                    Debug.LogWarning($"Failed to instantiate agent in a valid location after {tries} tries.");
                }
                else
                {
                    agents.Add(agent);
                }
            }
            return(agents);
        }
Esempio n. 45
0
        /// <inheritdoc />
        public unsafe override int BuildVertexBuffer(ref ParticleBufferState bufferState, Vector3 invViewX, Vector3 invViewY,
                                                     ref Vector3 spaceTranslation, ref Quaternion spaceRotation, float spaceScale, ref ParticleList sorter)
        {
            // Update the curve samplers if required
            base.BuildVertexBuffer(ref bufferState, invViewX, invViewY, ref spaceTranslation, ref spaceRotation, spaceScale, ref sorter);

            // Get all the required particle fields
            var positionField = sorter.GetField(ParticleFields.Position);

            if (!positionField.IsValid())
            {
                return(0);
            }
            var lifeField      = sorter.GetField(ParticleFields.Life);
            var sizeField      = sorter.GetField(ParticleFields.Size);
            var directionField = sorter.GetField(ParticleFields.Direction);

            // Check if the draw space is identity - in this case we don't need to transform the position, scale and rotation vectors
            var trsIdentity = (spaceScale == 1f);

            trsIdentity = trsIdentity && (spaceTranslation.Equals(new Vector3(0, 0, 0)));
            trsIdentity = trsIdentity && (spaceRotation.Equals(Quaternion.Identity));


            var renderedParticles = 0;

            var posAttribute = bufferState.GetAccessor(VertexAttributes.Position);
            var texAttribute = bufferState.GetAccessor(bufferState.DefaultTexCoords);

            Vector3 invViewZ;

            Vector3.Cross(ref invViewX, ref invViewY, out invViewZ);
            invViewZ.Normalize();

            foreach (var particle in sorter)
            {
                var centralPos = GetParticlePosition(particle, positionField, lifeField);

                var centralOffset = (directionField.IsValid()) ? particle.Get(directionField) : new Vector3(0, 1, 0);

                var particleSize = GetParticleSize(particle, sizeField, lifeField);

                if (!trsIdentity)
                {
                    spaceRotation.Rotate(ref centralPos);
                    centralPos = centralPos * spaceScale + spaceTranslation;

                    spaceRotation.Rotate(ref centralOffset);
                    centralOffset = centralOffset * spaceScale;

                    particleSize *= spaceScale;
                }

                var unitX = invViewX;
                var unitY = invViewY;

                {
                    var centralAxis = centralOffset;

                    float dotZ;
                    Vector3.Dot(ref centralAxis, ref invViewZ, out dotZ);
                    centralAxis -= invViewZ * dotZ;
                    centralAxis.Normalize();

                    float dotX;
                    Vector3.Dot(ref centralAxis, ref unitX, out dotX);

                    float dotY;
                    Vector3.Dot(ref centralAxis, ref unitY, out dotY);

                    unitX = unitX * dotY - unitY * dotX;
                    unitX.Normalize();

                    unitY = centralOffset;
                }

                // Use half size to make a Size = 1 result in a Billboard of 1m x 1m
                unitX *= (particleSize * 0.5f);
                if (ScaleLength)
                {
                    unitY *= (LengthFactor * particleSize * 0.5f);
                }
                else
                {
                    unitY *= (LengthFactor * 0.5f);
                }

                var particlePos = centralPos - unitX + unitY;
                var uvCoord     = new Vector2(0, 0);
                // 0f 0f
                bufferState.SetAttribute(posAttribute, (IntPtr)(&particlePos));
                bufferState.SetAttribute(texAttribute, (IntPtr)(&uvCoord));
                bufferState.NextVertex();


                // 1f 0f
                particlePos += unitX * 2;
                uvCoord.X    = 1;
                bufferState.SetAttribute(posAttribute, (IntPtr)(&particlePos));
                bufferState.SetAttribute(texAttribute, (IntPtr)(&uvCoord));
                bufferState.NextVertex();


                // 1f 1f
                particlePos -= unitY * 2;
                uvCoord.Y    = 1;
                bufferState.SetAttribute(posAttribute, (IntPtr)(&particlePos));
                bufferState.SetAttribute(texAttribute, (IntPtr)(&uvCoord));
                bufferState.NextVertex();


                // 0f 1f
                particlePos -= unitX * 2;
                uvCoord.X    = 0;
                bufferState.SetAttribute(posAttribute, (IntPtr)(&particlePos));
                bufferState.SetAttribute(texAttribute, (IntPtr)(&uvCoord));
                bufferState.NextVertex();

                renderedParticles++;
            }

            var vtxPerShape = 4 * QuadsPerParticle;

            return(renderedParticles * vtxPerShape);
        }
Esempio n. 46
0
        private void ComputeAngle(Hand hand)
        {
            Vector3 vector = this.ComputeToTransformProjected(hand.hoverSphereTransform);

            if (!vector.Equals(this.lastHandProjected))
            {
                float num = Vector3.Angle(this.lastHandProjected, vector);
                if (num > 0f)
                {
                    if (this.frozen)
                    {
                        float sqrMagnitude = (hand.hoverSphereTransform.position - this.frozenHandWorldPos).sqrMagnitude;
                        if (sqrMagnitude > this.frozenSqDistanceMinMaxThreshold.x)
                        {
                            this.outAngle = this.frozenAngle + UnityEngine.Random.Range(-1f, 1f);
                            float num2 = Util.RemapNumberClamped(sqrMagnitude, this.frozenSqDistanceMinMaxThreshold.x, this.frozenSqDistanceMinMaxThreshold.y, 0f, 1f);
                            if (num2 > 0f)
                            {
                                base.StartCoroutine(this.HapticPulses(hand.controller, num2, 10));
                            }
                            else
                            {
                                base.StartCoroutine(this.HapticPulses(hand.controller, 0.5f, 10));
                            }
                            if (sqrMagnitude >= this.frozenSqDistanceMinMaxThreshold.y)
                            {
                                this.onFrozenDistanceThreshold.Invoke();
                            }
                        }
                    }
                    else
                    {
                        Vector3 normalized = Vector3.Cross(this.lastHandProjected, vector).normalized;
                        float   num3       = Vector3.Dot(this.worldPlaneNormal, normalized);
                        float   num4       = num;
                        if (num3 < 0f)
                        {
                            num4 = -num4;
                        }
                        if (this.limited)
                        {
                            float num5 = Mathf.Clamp(this.outAngle + num4, this.minAngle, this.maxAngle);
                            if (this.outAngle == this.minAngle)
                            {
                                if (num5 > this.minAngle && num < this.minMaxAngularThreshold)
                                {
                                    this.outAngle          = num5;
                                    this.lastHandProjected = vector;
                                }
                            }
                            else if (this.outAngle == this.maxAngle)
                            {
                                if (num5 < this.maxAngle && num < this.minMaxAngularThreshold)
                                {
                                    this.outAngle          = num5;
                                    this.lastHandProjected = vector;
                                }
                            }
                            else if (num5 == this.minAngle)
                            {
                                this.outAngle          = num5;
                                this.lastHandProjected = vector;
                                this.onMinAngle.Invoke();
                                if (this.freezeOnMin)
                                {
                                    this.Freeze(hand);
                                }
                            }
                            else if (num5 == this.maxAngle)
                            {
                                this.outAngle          = num5;
                                this.lastHandProjected = vector;
                                this.onMaxAngle.Invoke();
                                if (this.freezeOnMax)
                                {
                                    this.Freeze(hand);
                                }
                            }
                            else
                            {
                                this.outAngle          = num5;
                                this.lastHandProjected = vector;
                            }
                        }
                        else
                        {
                            this.outAngle         += num4;
                            this.lastHandProjected = vector;
                        }
                    }
                }
            }
        }
Esempio n. 47
0
    public override IEnumerator DamagedAnimation(int oldHealth, Slider healthBar = null, StatusUI statusUI = null, Vector3 direction = new Vector3(), bool isCritical = false)
    {
        isMoving = true;
        float         frame = 16, frame2 = 0, frame3 = 10;
        Vector3       originalPosition = t.position;
        Color         originalColor    = GetComponent <SpriteRenderer>().color;
        DamagedScreen damagedScreen    = GameManager.gm.Canvas.GetComponent <UIInfo>().DamagedPanel;

        DamageNumber.DamageType dt = DamageNumber.DamageType.Normal;
        if (isCritical)
        {
            dt = DamageNumber.DamageType.Critical;
        }

        if (!direction.Equals(new Vector3()))
        {
            GameObject g = Instantiate(damageNumber, c.canvas.GetComponent <Transform>());
            g.GetComponent <DamageNumber>().Initialize(oldHealth - c.currentHealth, dt);
        }

        for (int i = 0; i < frame + frame2; i++)
        {
            if (i < frame / 2)
            {
                GetComponent <SpriteRenderer>().color = Color.Lerp(originalColor, new Color(0.7f, 0f, 0f, 0.6f), i / frame * 2);
                if (!direction.Equals(new Vector3()))
                {
                    t.position = Vector3.Lerp(originalPosition, originalPosition + 0.2f * direction, i / frame * 2);
                }
            }
            else
            {
                GetComponent <SpriteRenderer>().color = Color.Lerp(originalColor, new Color(0.7f, 0f, 0f, 0.6f), (frame + frame2 - i) / (frame / 2 + frame2));
                if (!direction.Equals(new Vector3()))
                {
                    t.position = Vector3.Lerp(originalPosition, originalPosition + 0.2f * direction, (frame + frame2 - i) / (frame / 2 + frame2));
                }
            }

            if (c.currentHealth <= c.MaxHealth / 6)
            {
                damagedScreen.StartEffect(true);
            }
            else if (c.currentHealth <= c.MaxHealth / 3)
            {
                damagedScreen.StartEffect(false);
            }

            if (i < frame)
            {
                float f = Mathf.Lerp(c.currentHealth, oldHealth, Mathf.Pow(1 - (i / frame), 2f));
                if (healthBar != null)
                {
                    healthBar.value = f;
                }
                if (statusUI != null)
                {
                    statusUI.UpdateAll(c, (int)f);
                }
            }

            yield return(null);
        }
        if (healthBar != null)
        {
            healthBar.value = c.currentHealth;
        }
        if (statusUI != null)
        {
            statusUI.UpdateAll(c, c.currentHealth);
        }
        GetComponent <SpriteRenderer>().color = originalColor;
        if (!direction.Equals(new Vector3()))
        {
            t.position = originalPosition;
        }

        for (int i = 0; i < frame3; i++)
        {
            yield return(null);
        }

        isMoving = false;
    }
Esempio n. 48
0
        public static int testEquals(Vector3 v0)
        {
            float f1 = (float)random.NextDouble();
            float f2 = (float)random.NextDouble();
            float f3 = (float)random.NextDouble();

            Vector3 v1 = new Vector3(f1, f2, f3) - v0;
            bool result = v1.Equals(getTestValue(f1, f2, f3) - v0);

            if ((result == false) || !v1.Equals(getTestValue(f1, f2, f3) - v0))
            {
                Console.WriteLine("Equals returns wrong value " + v1);
                return -1;
            }

            return 100;
        }
        public void DrawBoundaries()
        {
            Dictionary <Edge, int>    edges       = new Dictionary <Edge, int>();
            Dictionary <Vector3, int> allVertices = new Dictionary <Vector3, int>();

            foreach (var gameObject in gamesObjects)
            {
                if (gameObject.Value == null)
                {
                    continue;
                }

                Vector3[] verts = gameObject.Value.GetComponent <MeshFilter>().mesh.vertices;
                int[]     inds  = gameObject.Value.GetComponent <MeshFilter>().mesh.triangles;
                for (int i = 0; i < inds.Length; i += 3)
                {
                    Vector3[] triangleVert = new Vector3[3]; //這個triangle的三個點
                    for (int j = 0; j < 3; j++)              //看此點是否已經在已出現點的陣列裡面
                    {
                        triangleVert[j] = verts[inds[i + j]];

                        if (!allVertices.ContainsKey(triangleVert[j]))
                        {
                            allVertices.Add(triangleVert[j], allVertices.Count);
                        }
                    }

                    if (edges.ContainsKey(new Edge(triangleVert[0], triangleVert[1], triangleVert[2]))) //查看這個邊是否已經出現過,出現過就count + 1, 未出現就初始化這條邊
                    {
                        edges[new Edge(triangleVert[0], triangleVert[1], triangleVert[2])] += 1;
                    }
                    else
                    {
                        edges.Add(new Edge(triangleVert[0], triangleVert[1], triangleVert[2]), 1);
                    }

                    if (edges.ContainsKey(new Edge(triangleVert[0], triangleVert[2], triangleVert[1])))
                    {
                        edges[new Edge(triangleVert[0], triangleVert[2], triangleVert[1])] += 1;
                    }
                    else
                    {
                        edges.Add(new Edge(triangleVert[0], triangleVert[2], triangleVert[1]), 1);
                    }

                    if (edges.ContainsKey(new Edge(triangleVert[1], triangleVert[2], triangleVert[0])))
                    {
                        edges[new Edge(triangleVert[1], triangleVert[2], triangleVert[0])] += 1;
                    }
                    else
                    {
                        edges.Add(new Edge(triangleVert[1], triangleVert[2], triangleVert[0]), 1);
                    }
                }
            }

            List <Edge> singleEdges = new List <Edge>();

            foreach (var edge in edges) //等所有的邊都檢查過一次後,把count只有出現一次的邊取出來,並取出這條邊的兩個點在點陣列中的位置,然後丟進indices(用來之後要在mesh裡面把它畫出來)
            {
                if (edge.Value == 1)
                {
                    singleEdges.Add(edge.Key);
                    //indices.Add(allVertices[edge.Key.v1]);
                    //indices.Add(allVertices[edge.Key.v2]);
                }
            }
            edges.Clear();

            List <List <Vector3> > Vertices      = new List <List <Vector3> >();
            List <Vector3>         vertices      = new List <Vector3>();
            List <List <Vector3> > ThirdVertices = new List <List <Vector3> >();
            List <Vector3>         thirdvertices = new List <Vector3>();

            vertices.Add(singleEdges[0].v1);
            vertices.Add(singleEdges[0].v2);
            thirdvertices.Add(singleEdges[0].v3);
            singleEdges.RemoveAt(0);
            int k = 0;

            while (singleEdges.Count != 0)
            {
                if (Vector3.Equals(singleEdges[k].v1, vertices.Last()))
                {
                    vertices.Add(singleEdges[k].v2);
                    thirdvertices.Add(singleEdges[k].v3);
                    singleEdges.RemoveAt(k);
                    k = 0;
                }
                else if (Vector3.Equals(singleEdges[k].v2, vertices.Last()))
                {
                    vertices.Add(singleEdges[k].v1);
                    thirdvertices.Add(singleEdges[k].v3);
                    singleEdges.RemoveAt(k);
                    k = 0;
                }
                else if (k == singleEdges.Count - 1)
                {
                    Vertices.Add(vertices.ToList());
                    vertices.Clear();
                    ThirdVertices.Add(thirdvertices.ToList());
                    thirdvertices.Clear();
                    vertices.Add(singleEdges[0].v1);
                    vertices.Add(singleEdges[0].v2);
                    thirdvertices.Add(singleEdges[0].v3);
                    singleEdges.RemoveAt(0);
                    k = 0;
                }
                else
                {
                    k += 1;
                }
            }

            Vertices.Add(vertices.ToList());
            vertices.Clear();
            ThirdVertices.Add(thirdvertices.ToList());
            thirdvertices.Clear();

            List <int> indices = new List <int>();

            for (int i = 0; i < Vertices.Count; i++)
            {
                if (!PointInsidePolygon(ThirdVertices[i], Vertices[i]))
                {
                    Mesh temp = new Mesh();
                    temp.vertices = Vertices[i].ToArray();
                    Vector3 center = temp.bounds.center;
                    allVertices.Add(center, allVertices.Count);
                    for (int j = 0; j < Vertices[i].Count - 1; j++)
                    {
                        indices.Add(allVertices[Vertices[i][j]]);
                        indices.Add(allVertices[center]);
                        indices.Add(allVertices[Vertices[i][j + 1]]);
                        indices.Add(allVertices[Vertices[i][j + 1]]);
                        indices.Add(allVertices[center]);
                        indices.Add(allVertices[Vertices[i][j]]);
                    }

                    /* float area = 0f;
                     * List<int> tempIndices = new List<int>();
                     * for (int j = 0; j < Vertices[i].Count - 1; j++)
                     * {
                     *  tempIndices.Add(allVertices[Vertices[i][j]]);
                     *  tempIndices.Add(allVertices[center]);
                     *  tempIndices.Add(allVertices[Vertices[i][j + 1]]);
                     *  tempIndices.Add(allVertices[Vertices[i][j + 1]]);
                     *  tempIndices.Add(allVertices[center]);
                     *  tempIndices.Add(allVertices[Vertices[i][j]]);
                     *  area += Vector3.Cross(Vertices[i][j]-center, Vertices[i][j+1]-center).magnitude * 0.5f;
                     * }
                     * if(area >= 0.09)
                     * {
                     *  indices.AddRange(tempIndices);
                     * }
                     * else
                     * {
                     *  allVertices.Remove(center);
                     * }*/
                }
            }

            Vector3[] vertss = new Vector3[allVertices.Keys.Count];
            allVertices.Keys.CopyTo(vertss, 0);

            List <Color> colors = new List <Color>();

            for (int i = 0; i < allVertices.Count; i++)
            {
                colors.Add(Color.red);
            }

            // 畫mesh
            insideBoundary = Instantiate(mesh);
            insideBoundary.SetActive(true);
            insideBoundary.GetComponent <MeshFilter>().mesh.vertices = vertss;
            insideBoundary.GetComponent <MeshFilter>().mesh.SetIndices(indices.ToArray(), MeshTopology.Triangles, 0, false);
            insideBoundary.GetComponent <MeshFilter>().mesh.colors = colors.ToArray();
        }
Esempio n. 50
0
        public bool IsCreatedIn(float radius)
        {
            if (relationship == 0)
            {
                return(false);
            }

            Vector3 safePosition = Util.GetSafePositionIn(radius);

            if (safePosition.Equals(Vector3.Zero))
            {
                Logger.Error("Terrorist: Couldn't find safe position. Abort.", name);

                return(false);
            }

            for (int cnt = 0; cnt < 5; cnt++)
            {
                Road road = Util.GetNextPositionOnStreetWithHeading(safePosition.Around(50.0f));

                if (road != null)
                {
                    Logger.Write(false, "Terrorist: Found proper road.", name);
                    spawnedVehicle = Util.Create(name, road.Position, road.Heading, true);

                    if (!Util.ThereIs(spawnedVehicle))
                    {
                        Logger.Write(false, "Terrorist: Couldn't create vehicle.", name);
                        Restore(true);

                        continue;
                    }

                    Logger.Write(false, "Terrorist: Created vehicle and driver.", name);
                    Script.Wait(50);
                    Util.Tune(spawnedVehicle, false, false, false);

                    if (name == "khanjali" && spawnedVehicle.GetMod(VehicleMod.Roof) != -1)
                    {
                        spawnedVehicle.SetMod(VehicleMod.Roof, -1, false);
                    }

                    for (int i = -1; i < spawnedVehicle.PassengerSeats; i++)
                    {
                        if (spawnedVehicle.IsSeatFree((VehicleSeat)i))
                        {
                            members.Add(spawnedVehicle.CreatePedOnSeat((VehicleSeat)i, "g_m_m_chicold_01"));
                            Script.Wait(50);
                        }
                    }

                    Logger.Write(false, "Terrorist: Tuned vehicle and created members.", name);

                    if (members.Find(p => !Util.ThereIs(p)) != null)
                    {
                        Logger.Write(false, "Terrorist: There is a member who doesn't exist.", name);
                        Restore(true);

                        continue;
                    }

                    foreach (Ped p in members)
                    {
                        Util.SetCombatAttributesOf(p);
                        p.RelationshipGroup          = relationship;
                        p.IsPriorityTargetForEnemies = true;
                        p.CanBeShotInVehicle         = false;

                        p.Weapons.Give(WeaponHash.MicroSMG, 100, true, true);
                        p.Weapons.Current.InfiniteAmmo = true;
                        p.FiringPattern = FiringPattern.BurstFireDriveby;

                        p.AlwaysKeepTask       = true;
                        p.BlockPermanentEvents = true;
                        p.Task.FightAgainstHatedTargets(400.0f);
                        Logger.Write(false, "Terrorist: Characteristics are set.", name);
                    }

                    if (SpawnedPedExistsIn(members))
                    {
                        Logger.Write(false, "Terrorist: Created terrorists successfully.", name);
                        blipName += VehicleInfo.GetNameOf(spawnedVehicle.Model.Hash);

                        return(true);
                    }
                    else
                    {
                        Logger.Write(false, "Terrorist: Driver doesn't exist.", name);
                        Restore(true);
                    }
                }
            }

            Logger.Error("Terrorist: Couldn't find proper road. Abort.", name);

            return(false);
        }
 public bool Equals(Edge other)
 {
     if ((Vector3.Equals(this.v1, other.v1) && Vector3.Equals(this.v2, other.v2)) || (Vector3.Equals(this.v1, other.v2) && Vector3.Equals(this.v2, other.v1)))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Esempio n. 52
0
        /// <summary>
        /// Combines all submeshes into the mesh on this object.
        /// </summary>
        public void Combine()
        {
            //get all mesh filters, but don't continue if there are no submeshes
            MeshFilter[] meshFilters = GetComponentsInChildren <MeshFilter>();

            //get the mesh filter on this object
            MeshFilter             myFilter = meshFilters[0];
            List <CombineInstance> combine  = new List <CombineInstance>();

            //add meshes to the combine instances
            for (int i = 0; i < meshFilters.Length; i++)
            {
                if (meshFilters[i].sharedMesh == null)
                {
                    continue;
                }

                CombineInstance c = new CombineInstance();
                c.mesh      = meshFilters[i].sharedMesh;
                c.transform = meshFilters[i].transform.localToWorldMatrix;
                combine.Add(c);
            }

            //rename mesh to a more appropriate name or keep it
            string meshName = "NavMesh";

            if (myFilter.sharedMesh != null)
            {
                meshName = myFilter.sharedMesh.name;
            }

            //create new shared mesh from combined meshes
            myFilter.sharedMesh      = new Mesh();
            myFilter.sharedMesh.name = meshName;
            myFilter.sharedMesh.CombineMeshes(combine.ToArray());
            current.Clear();

            //list of vertices and triangles
            List <Vector3> vertices  = new List <Vector3>(myFilter.sharedMesh.vertices);
            List <int>     triangles = new List <int>(myFilter.sharedMesh.triangles);

            //convert vertex positions into relative positions
            for (int i = 0; i < vertices.Count; i++)
            {
                vertices[i] = transform.InverseTransformPoint(vertices[i]);
            }

            /*
             * string str = "";
             * for (int i = 0; i < triangles.Count; i++)
             *  str += triangles[i] + " ";
             *
             * Debug.Log("BEFORE tris: " + str);
             */

            //find duplicated vertex positions
            List <int>     dupIndices = new List <int>();
            List <Vector3> duplicates = vertices.GroupBy(x => x)
                                        .Where(x => x.Count() > 1)
                                        .Select(x => x.Key)
                                        .ToList();

            //Debug.Log("duplicates: " + duplicates.Count);

            //loop over duplicates to find vertex indices,
            //also overwrite indices with the first occurence in the triangle array
            for (int i = 0; i < duplicates.Count; i++)
            {
                //get all occurences of duplicated indices
                List <int> indices = vertices.Select((value, index) => new { value, index })
                                     .Where(a => Vector3.Equals(a.value, duplicates[i]))
                                     .Select(a => a.index).ToList();

                //get first occurence
                int unique = indices[0];
                indices.RemoveAt(0);

                //loop over duplicated indices
                for (int j = 0; j < indices.Count; j++)
                {
                    //get this duplicate
                    int dupIndex = indices[j];
                    //get all matches in the triangle array
                    List <int> matches = Enumerable.Range(0, triangles.Count)
                                         .Where(v => triangles[v] == dupIndex)
                                         .ToList();

                    //overwrite duplicated matches with the unique index
                    for (int k = 0; k < matches.Count; k++)
                    {
                        //Debug.Log("overwriting index: " + matches[j] + " with: " + first);
                        triangles[matches[k]] = unique;
                    }

                    //remember for later, when we are merging vertices
                    dupIndices.Add(dupIndex);
                }
            }

            //sort duplicated indices in a descending order
            dupIndices = dupIndices.OrderByDescending(x => x).ToList();

            //loop over indices
            for (int i = 0; i < dupIndices.Count; i++)
            {
                //remove the vertex
                int dupIndex = dupIndices[i];
                vertices.RemoveAt(dupIndex);

                //decrease indices starting after this vertex,
                //since we removed it and the array is smaller now
                for (int j = dupIndex; j < triangles.Count; j++)
                {
                    if (triangles[j] >= dupIndex)
                    {
                        triangles[j] = triangles[j] - 1;
                    }
                }
            }

            /*
             * str = "";
             * for (int i = 0; i < triangles.Count; i++)
             *  str += triangles[i] + " ";
             *
             * Debug.Log("AFTER tris: " + str);
             */
            //Debug.Log("COUNTS: " + vertices.Count + " " + triangles.Count);

            //assign merged vertices and triangles to the new mesh
            myFilter.sharedMesh.triangles = triangles.ToArray();
            myFilter.sharedMesh.vertices  = vertices.ToArray();

            //recalculate and optimize
            myFilter.sharedMesh.RecalculateNormals();
            myFilter.sharedMesh.RecalculateBounds();
            myFilter.sharedMesh.Optimize();
        }
Esempio n. 53
0
    int[] FindFacesUsing(Vector3 p, Vector3 n)
    {
        List<int> faces = new List<int>();
        Vector3 v = Vector3.zero;

        for ( int i = 0; i < otris.Length; i += 3 )
        {
            v = overts[otris[i]];
            if ( v.x == p.x && v.y == p.y && v.z == p.z )
            {
                if ( n.Equals(norms[otris[i]]) )
                    faces.Add(i / 3);
            }
            else
            {
                v = overts[otris[i + 1]];
                if ( v.x == p.x && v.y == p.y && v.z == p.z )
                {
                    if ( n.Equals(norms[otris[i + 1]]) )
                        faces.Add(i / 3);
                }
                else
                {
                    v = overts[otris[i + 2]];
                    if ( v.x == p.x && v.y == p.y && v.z == p.z )
                    {
                        if ( n.Equals(norms[otris[i + 2]]) )
                            faces.Add(i / 3);
                    }
                }
            }
        }

        return faces.ToArray();
        //return faces;
    }
Esempio n. 54
0
    // Update is called once per frame
    void Update()
    {
        animator.SetBool("isWalking", false);
        h = Input.GetAxis("Horizontal");
        v = Input.GetAxis("Vertical");

        dir = xdir + ydir;

        if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
        {
            transform.Translate(new Vector3(-0.6f * movingSpd * Time.deltaTime, 0, 0)); //0.6f는 해당 방향으로 프레임당 얼마씩 움직일지 정하는숫자.
            //Debug.Log(movingSpd * Time.deltaTime);

            isWalking = true;
            animator.SetFloat("Direction_X", h);
            animator.SetFloat("Direction_Y", v);
            animator.SetBool("isWalking", isWalking);

            getPlayerDirection();
        }
        if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
        {
            transform.Translate(new Vector3(0.6f * movingSpd * Time.deltaTime, 0, 0));

            isWalking = true;
            animator.SetFloat("Direction_X", h);
            animator.SetFloat("Direction_Y", v);
            animator.SetBool("isWalking", isWalking);

            getPlayerDirection();
        }
        if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
        {
            transform.Translate(new Vector3(0, 0.6f * movingSpd * Time.deltaTime, 0));
            isWalking = true;
            animator.SetFloat("Direction_X", h);
            animator.SetFloat("Direction_Y", v);
            animator.SetBool("isWalking", isWalking);

            getPlayerDirection();
        }
        if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
        {
            transform.Translate(new Vector3(0, -0.6f * movingSpd * Time.deltaTime, 0));
            isWalking = true;
            animator.SetFloat("Direction_X", h);
            animator.SetFloat("Direction_Y", v);
            animator.SetBool("isWalking", isWalking);

            getPlayerDirection();
        }
        if (Input.GetKeyDown(KeyCode.C))
        {
            guntype += 1;
            if (guntype == 3)
            {
                guntype = 0;
            }
        }
        if (Input.GetKeyDown(KeyCode.Q))
        {
            SoundManager.instance.bgSource.Pause();
            SoundManager.instance.ChangeBgAudio(voyagerSound1); //FIXME - 배열화
        }
        if (Input.GetKeyDown(KeyCode.E))
        {
            SoundManager.instance.bgSource.Pause();
            SoundManager.instance.ChangeBgAudio(voyagerSound2); // FIXME - 배열화

            //SoundManager.instance.bgSource.Stop();
        }
        if (Input.GetKeyDown(KeyCode.LeftShift))    // dash
        // transform.SetPositionAndRotation(new Vector3(),Quaternion.identity);
        {
            Instantiate(dashEffect, transform.position, Quaternion.identity);
            isDashing = true;

            // Vector3 move = 0.6f * dir * 10f;
            // Debug.Log("move: " + move);
            // transform.Translate(move); //FIXME
            if (dashTime <= 0)
            {
                dir      = new Vector3(0, 0, 0); // why??
                dashTime = startDashTime;
                animator.SetBool("isDashing", false);
                transform.Translate(new Vector3(0, 0, 0));
            }
            else
            {
                if (!Vector3.Equals(dir, new Vector3(0, 0, 0))) //없어도 되지않나?
                {
                }
            }

            //animator.SetBool("isDashing", isDashing);
        }
        if (dashTime <= 0)
        {
            animator.SetBool("isDashing", false);
            isDashing = false;
        }

        if (isDashing)
        {
            animator.SetBool("isDashing", true);
            dir.Normalize(); //없애보고 테스트 필요.
            dashTime -= Time.deltaTime;
            if (animator.GetCurrentAnimatorStateInfo(0).IsName("TempRolling"))
            {
                transform.Translate(dir * dashSpeed * Time.deltaTime);
            }

            animator.SetFloat("Direction_X", h);
            animator.SetFloat("Direction_Y", v);
        }
    }
Esempio n. 55
0
        public int CompareFlowVectors(Vector3 A, Vector3 B, Vector3 flow)
        {
            if(A.Equals(B))
            {
                return 0;
            }
            else
            {
                float dotA = Vector3.Dot(A, flow);
                float dotB = Vector3.Dot(B, flow);

                if(dotA > dotB)
                {
                    return 1;
                }
                else
                {
                    return -1;
                }
            }
        }
Esempio n. 56
0
        /// <summary>
        /// Moves, scales, and/or rotates the current entity given a 3x3 transformation matrix and a translation vector.
        /// </summary>
        /// <param name="transformation">Transformation matrix.</param>
        /// <param name="translation">Translation vector.</param>
        /// <remarks>Matrix3 adopts the convention of using column vectors to represent a transformation matrix.</remarks>
        public override void TransformBy(Matrix3 transformation, Vector3 translation)
        {
            // NOTE: this is a generic implementation of the ellipse transformation,
            // for non rotated ellipses and/or uniform scaling the code can be simplified

            // rectangle that circumscribe the ellipse
            double semiMajorAxis = this.MajorAxis * 0.5;
            double semiMinorAxis = this.MinorAxis * 0.5;

            Vector2        p1        = new Vector2(-semiMajorAxis, semiMinorAxis);
            Vector2        p2        = new Vector2(semiMajorAxis, semiMinorAxis);
            Vector2        p3        = new Vector2(-semiMajorAxis, -semiMinorAxis);
            Vector2        p4        = new Vector2(semiMajorAxis, -semiMinorAxis);
            List <Vector2> ocsPoints = MathHelper.Transform(new[] { p1, p2, p3, p4 }, this.Rotation * MathHelper.DegToRad, CoordinateSystem.Object, CoordinateSystem.World);

            Vector3        p1Prime   = new Vector3(ocsPoints[0].X, ocsPoints[0].Y, 0.0);
            Vector3        p2Prime   = new Vector3(ocsPoints[1].X, ocsPoints[1].Y, 0.0);
            Vector3        p3Prime   = new Vector3(ocsPoints[2].X, ocsPoints[2].Y, 0.0);
            Vector3        p4Prime   = new Vector3(ocsPoints[3].X, ocsPoints[3].Y, 0.0);
            List <Vector3> wcsPoints = MathHelper.Transform(new[] { p1Prime, p2Prime, p3Prime, p4Prime }, this.Normal, CoordinateSystem.Object, CoordinateSystem.World);

            for (int i = 0; i < wcsPoints.Count; i++)
            {
                wcsPoints[i] += this.Center;

                wcsPoints[i]  = transformation * wcsPoints[i];
                wcsPoints[i] += translation;
            }

            Vector3 newNormal = transformation * this.Normal;

            if (Vector3.Equals(Vector3.Zero, newNormal))
            {
                newNormal = this.Normal;
            }

            List <Vector3> rectPoints = MathHelper.Transform(wcsPoints, newNormal, CoordinateSystem.World, CoordinateSystem.Object);

            // corners of the transformed rectangle that circumscribe the new ellipse
            Vector2 pointA = new Vector2(rectPoints[0].X, rectPoints[0].Y);
            Vector2 pointB = new Vector2(rectPoints[1].X, rectPoints[1].Y);
            Vector2 pointC = new Vector2(rectPoints[2].X, rectPoints[2].Y);
            Vector2 pointD = new Vector2(rectPoints[3].X, rectPoints[3].Y);

            // the new ellipse is tangent at the mid points
            Vector2 pointM = Vector2.MidPoint(pointA, pointB);
            Vector2 pointN = Vector2.MidPoint(pointC, pointD);
            Vector2 pointH = Vector2.MidPoint(pointA, pointC);
            Vector2 pointK = Vector2.MidPoint(pointB, pointD);

            // we need to find a fifth point
            Vector2 origin = Vector2.MidPoint(pointH, pointK);
            Vector2 pointX = Vector2.MidPoint(pointH, origin); // a point along the OH segment

            // intersection line AC and line parallel to BC through pointX
            Vector2 pointY = MathHelper.FindIntersection(pointA, pointC - pointA, pointX, pointC - pointB);

            if (Vector2.IsNaN(pointY))
            {
                Debug.Assert(false, "The transformation cannot be applied.");
                return;
            }

            // find the fifth point in the ellipse
            Vector2 pointZ = MathHelper.FindIntersection(pointM, pointX - pointM, pointN, pointY - pointN);

            if (Vector2.IsNaN(pointZ))
            {
                Debug.Assert(false, "The transformation cannot be applied.");
                return;
            }

            Vector3 oldNormal   = this.Normal;
            double  oldRotation = this.Rotation;

            Vector2 newCenter;
            double  newSemiMajorAxis;
            double  newSemiMinorAxis;
            double  newRotation;

            if (ConicThroughFivePoints.EllipseProperties(pointM, pointN, pointH, pointK, pointZ, out newCenter, out newSemiMajorAxis, out newSemiMinorAxis, out newRotation))
            {
                double axis1 = 2 * newSemiMajorAxis;
                axis1 = MathHelper.IsZero(axis1) ? MathHelper.Epsilon : axis1;
                double axis2 = 2 * newSemiMinorAxis;
                axis2 = MathHelper.IsZero(axis2) ? MathHelper.Epsilon : axis2;

                this.Center    = transformation * this.Center + translation;
                this.MajorAxis = axis1;
                this.MinorAxis = axis2;
                this.Rotation  = newRotation * MathHelper.RadToDeg;
                this.Normal    = newNormal;
            }
            else
            {
                Debug.Assert(false, "The transformation cannot be applied.");
                return;
            }

            if (this.IsFullEllipse)
            {
                return;
            }

            //if not full ellipse calculate start and end angles
            Vector2 start = this.PolarCoordinateRelativeToCenter(this.StartAngle);
            Vector2 end   = this.PolarCoordinateRelativeToCenter(this.EndAngle);

            if (!MathHelper.IsZero(oldRotation))
            {
                double beta    = oldRotation * MathHelper.DegToRad;
                double sinBeta = Math.Sin(beta);
                double cosBeta = Math.Cos(beta);

                start = new Vector2(start.X * cosBeta - start.Y * sinBeta, start.X * sinBeta + start.Y * cosBeta);
                end   = new Vector2(end.X * cosBeta - end.Y * sinBeta, end.X * sinBeta + end.Y * cosBeta);
            }

            Vector3 pStart = new Vector3(start.X, start.Y, 0.0);
            Vector3 pEnd   = new Vector3(end.X, end.Y, 0.0);

            List <Vector3> wcsAnglePoints = MathHelper.Transform(new[] { pStart, pEnd }, oldNormal, CoordinateSystem.Object, CoordinateSystem.World);

            for (int i = 0; i < wcsAnglePoints.Count; i++)
            {
                wcsPoints[i] += this.Center;

                wcsAnglePoints[i] = transformation * wcsAnglePoints[i];
                wcsPoints[i]     += translation;
            }

            List <Vector3> ocsAnglePoints = MathHelper.Transform(wcsAnglePoints, newNormal, CoordinateSystem.World, CoordinateSystem.Object);

            Vector2 newStart = new Vector2(ocsAnglePoints[0].X, ocsAnglePoints[0].Y);
            Vector2 newEnd   = new Vector2(ocsAnglePoints[1].X, ocsAnglePoints[1].Y);

            if (Math.Sign(transformation.M11 * transformation.M22 * transformation.M33) < 0)
            {
                this.EndAngle   = Vector2.Angle(newStart) * MathHelper.RadToDeg;
                this.StartAngle = Vector2.Angle(newEnd) * MathHelper.RadToDeg;
            }
            else
            {
                this.StartAngle = Vector2.Angle(newStart) * MathHelper.RadToDeg;
                this.EndAngle   = Vector2.Angle(newEnd) * MathHelper.RadToDeg;
            }
        }
Esempio n. 57
0
 public bool Equals(VertexPosition other)
 {
     return(Position.Equals(other.Position));
 }
Esempio n. 58
0
        /// <inheritdoc />
        public override unsafe int BuildVertexBuffer(ref ParticleBufferState bufferState, Vector3 invViewX, Vector3 invViewY,
                                                     ref Vector3 spaceTranslation, ref Quaternion spaceRotation, float spaceScale, ref ParticleList sorter, ref Matrix viewProj)
        {
            // Get all the required particle fields
            var positionField = sorter.GetField(ParticleFields.Position);

            if (!positionField.IsValid())
            {
                return(0);
            }
            var sizeField      = sorter.GetField(ParticleFields.Size);
            var directionField = sorter.GetField(ParticleFields.Direction);

            // Check if the draw space is identity - in this case we don't need to transform the position, scale and rotation vectors
            var trsIdentity = (spaceScale == 1f);

            trsIdentity = trsIdentity && (spaceTranslation.Equals(new Vector3(0, 0, 0)));
            trsIdentity = trsIdentity && (spaceRotation.Equals(Quaternion.Identity));

            var ribbonizer = new Ribbonizer(this, currentTotalParticles, currentQuadsPerParticle);

            var renderedParticles = 0;

            bufferState.StartOver();

            uint oldOrderValue = 0;
            var  orderField    = sorter.GetField(ParticleFields.Order);

            foreach (var particle in sorter)
            {
                if (orderField.IsValid())
                {
                    var orderValue = (*((uint *)particle[orderField]));

                    if ((orderValue >> SpawnOrderConst.GroupBitOffset) != (oldOrderValue >> SpawnOrderConst.GroupBitOffset))
                    {
                        ribbonizer.Ribbonize(ref bufferState, QuadsPerParticle);
                        ribbonizer.RibbonSplit();
                    }

                    oldOrderValue = orderValue;
                }

                var centralPos = particle.Get(positionField);

                var particleSize      = sizeField.IsValid() ? particle.Get(sizeField) : 1f;
                var particleDirection = directionField.IsValid() ? particle.Get(directionField) * particleSize : new Vector3(0f, particleSize, 0f);

                if (!trsIdentity)
                {
                    spaceRotation.Rotate(ref centralPos);
                    centralPos = centralPos * spaceScale + spaceTranslation;

                    // Direction
                    spaceRotation.Rotate(ref particleDirection);
                    particleDirection *= spaceScale;
                }

                ribbonizer.AddParticle(ref centralPos, ref particleDirection);

                renderedParticles++;
            }

            ribbonizer.Ribbonize(ref bufferState, QuadsPerParticle);

            ribbonizer.Free();

            var vtxPerShape = 4 * QuadsPerParticle;

            return(renderedParticles * vtxPerShape);
        }
	/// <summary>
	/// Sets the current target of the ray.
	/// </summary>
	/// 
	public void OverrideRayTarget(Vector3 pos)
	{
		if (pos.Equals(Vector3.zero))
		{
			overrideTarget = false;
		}
		else
		{
			overrideTarget = true;
			rayTarget.point = pos;
		}
	}
Esempio n. 60
0
    protected virtual void InitAstar(Path path)
    {
        this.path = path;

        _start = gridScript.start;
        _goal  = gridScript.goal;

        _gridWidth  = gridScript.gridWidth;
        _gridHeight = gridScript.gridHeight;

        _pos = gridScript.GetGrid();

        _frontier = new PriorityQueue <Vector3>();
        _frontier.Enqueue(_start, 0);

        _cameFrom.Add(_start, _start);
        _costSoFar.Add(_start, 0);

        var exploredNodes = 0;

        while (_frontier.Count != 0)
        {
            exploredNodes++;
            _current = _frontier.Dequeue();

            _visited.Add(_current);

            // _pos[(int)_current.x, (int)_current.y].transform.localScale = Vector3.Scale(_pos[(int)_current.x, (int)_current.y].transform.localScale, new Vector3(.8f, .8f, .8f));

            if (_current.Equals(_goal))
            {
                Debug.Log("GOOOAL!");
                break;
            }

            for (var y = -1; y < 2; y += 2)
            {
                AddNodesToFrontier((int)_current.x, (int)_current.y + y);
            }

            for (var x = -1; x < 2; x += 2)
            {
                AddNodesToFrontier((int)_current.x + x, (int)_current.y);
            }
        }

        _current = _goal;

        var line = GetComponent <LineRenderer>();

        var   i     = 0;
        float score = 0;

        while (!_current.Equals(_start))
        {
            line.positionCount++;

            var go = _pos[(int)_current.x, (int)_current.y];
            path.Insert(0, go, new Vector3((int)_current.x, (int)_current.y));

            _current = _cameFrom[_current];

            var vec = Util.clone(go.transform.position);
            vec.z = -1;

            line.SetPosition(i, vec);
            score += gridScript.GetMovementCost(go);
            i++;
        }

        path.Insert(0, _pos[(int)_current.x, (int)_current.y]);
        path.nodeInspected = exploredNodes;

        Debug.Log(path.pathName + " Terrain Score: " + score);
        Debug.Log(path.pathName + " Nodes Checked: " + exploredNodes);
        Debug.Log(path.pathName + " Total Score: " + (score + exploredNodes));
    }