Fix64Vector2 FindClosestVector2() { GameObject[] Allthem = GameObject.FindGameObjectsWithTag("Player"); Fix64 sqrdis = Fix64.MaxValue; Fix64Vector2 position = (Fix64Vector2)GetComponent <Rigidbody2D>().position; Fix64Vector2 vector = (Fix64Vector2)GetComponent <Rigidbody2D>().velocity; foreach (GameObject Him in Allthem) { //Debug.Log(Him.name); if (Him == sender) { continue; //跳过施法者 } Fix64Vector2 diff = ((Fix64Vector2)Him.GetComponent <Rigidbody2D>().position - position); Fix64 curDistance = diff.LengthSquare(); //向量距离平方 if (curDistance <= sqrdis) { sqrdis = curDistance; //更新最近距离 vector = diff; //更新向量 } //Debug.Log(vector.LengthSquare()); } Fix64Vector2 v2r = (vector.normalized() * speed); return(v2r); }
GameObject FindClosestEnemy(Vector2 findingplace) { GameObject closest = null; // GameObject.FindWithTag("Player"); GameObject[] Allthem = GameObject.FindGameObjectsWithTag("Player"); float sqrdis = Mathf.Infinity; foreach (GameObject Him in Allthem) { if (Him == gameObject) continue;//跳过施法者 Vector2 diff = (Him.GetComponent<Rigidbody2D>().position - findingplace); //距离向量 float curDistance = diff.sqrMagnitude; //距离平方 if (curDistance < sqrdis) { closest = Him; //更新最近距离敌人 sqrdis = curDistance; //更新最近距离 } } return closest; }
GameObject FindClosestEnemy() { GameObject closest = null; // GameObject.FindWithTag("Player"); GameObject[] Allthem = GameObject.FindGameObjectsWithTag("Player"); Fix64 sqrdis = Fix64.MaxValue; Fix64Vector2 position = (Fix64Vector2)GetComponent <Rigidbody2D>().position; foreach (GameObject Him in Allthem) { if (Him == sender) { continue; //跳过施法者 } Fix64Vector2 diff = ((Fix64Vector2)Him.GetComponent <Rigidbody2D>().position - position); //距离向量 Fix64 curDistance = diff.LengthSquare(); //距离平方 if (curDistance < sqrdis) { closest = Him; //更新最近距离敌人 sqrdis = curDistance; //更新最近距离 } } return(closest); }