当它是正方形时我可以设置空间很好。 但我不知道如何用圆圈形成。 在FormationSquare方法中,我使用空间变量进行方形形成。现在我也需要对圆形的形成做同样的想法。
也许在RandomCircle里面改变一些东西并使用空间变量?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SquadFormation : MonoBehaviour
{
enum Formation
{
Square, Circle
}
public Transform squadMemeber;
public int columns = 4;
public int space = 10;
public int numObjects = 20;
public float yOffset = 1;
private Formation formation;
// Use this for initialization
void Start()
{
formation = Formation.Square;
ChangeFormation();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
GameObject[] objects = GameObject.FindGameObjectsWithTag("Squad Member");
if (objects.Length > 0)
{
foreach (GameObject obj in objects)
Destroy(obj);
}
ChangeFormation();
}
}
private void ChangeFormation()
{
switch (formation)
{
case Formation.Square:
for (int i = 0; i < 23; i++)
{
Transform go = Instantiate(squadMemeber);
Vector3 pos = FormationSquare(i);
go.position = new Vector3(transform.position.x + pos.x, 0, transform.position.y + pos.y);
go.Rotate(new Vector3(0, -90, 0));
go.tag = "Squad Member";
}
formation = Formation.Circle;
break;
case Formation.Circle:
Vector3 center = transform.position;
for (int i = 0; i < numObjects; i++)
{
Vector3 pos = RandomCircle(center, 5.0f);
var rot = Quaternion.LookRotation(center - pos);
pos.y = Terrain.activeTerrain.SampleHeight(pos);
pos.y = pos.y + yOffset;
Transform insObj = Instantiate(squadMemeber, pos, rot);
insObj.rotation = rot;
insObj.tag = "Squad Member";
}
formation = Formation.Square;
break;
}
}
Vector2 FormationSquare(int index) // call this func for all your objects
{
float posX = (index % columns) * space;
float posY = (index / columns) * space;
return new Vector2(posX, posY);
}
Vector3 RandomCircle(Vector3 center, float radius)
{
float ang = Random.value * 360;
Vector3 pos;
pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
pos.z = center.z + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
pos.y = center.y;
return pos;
}
}
答案 0 :(得分:2)
这里的问题是你的RandomCircle()
方法是......好吧,随机。你只是随意地围绕圆圈抓住一个角度,而不考虑其他小队成员的位置,这意味着他们实际上永远不会均匀分布。
考虑计算将每个小队成员分开的角度(如果均匀分布),然后对FormationSquare()
执行类似的方法,在那里迭代小队以分发它们。
这可能更接近你想要的东西(基于假设RandomCircle()
已经按设计工作):
Vector3 FormationCircle(Vector3 center, float radius, int index, float angleIncrement)
{
float ang = index * angleIncrement;
Vector3 pos;
pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
pos.z = center.z + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
pos.y = center.y;
return pos;
}
要打电话,你可以这样做:
Vector3 center = transform.position;
float radius = (float)space / 2;
float angleIncrement = 360 / (float)numObjects;
for (int i = 0; i < numObjects; i++)
{
Vector3 pos = FormationCircle(center, radius, i, angleIncrement);
// ...
}
希望这有帮助!如果您有任何问题,请告诉我。