如果您有圆的半径,则在圆的一个片段中实例化游戏对象

时间:2017-05-10 15:16:42

标签: c# algorithm unity3d

我想在一个圆圈中实例化游戏对象,例如距离已知的vector3位置在10度到100度之间。 (想象一下比萨饼的形状)。我发现以下代码可以帮助我实例化0到180度之间的对象。有人可以帮助我实例化10到100度之间的游戏对象。

Vector3 randomCircle ( Vector3 center ,   float radius )
{
    float ang = Random.value * 180;
    Vector3 pos;
    pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
    pos.y = center.y + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
    pos.z = center.z;
    return pos;
}

1 个答案:

答案 0 :(得分:0)

将我的answer复制并修改为不同的主题可以满足您的需求。

// get the new position 
public Vector3 OrbitPosition(Vector3 centerPoint, float radius, float angle)
{
    Vector3 tmp;
    // calculate position X
    tmp.x = Mathf.Sin(angle * (Mathf.PI / 180)) * radius + centerPoint.x;
    // calculate position Y
    tmp.y = Mathf.Sin(angle * (Mathf.PI / 180)) * radius + centerPoint.y;
    tmp.z = centerPoint.z;
    return tmp;
}

// instantiate element at random orbit position
public GameObject InstantiateRandom(GameObject toInstantiate, Vector3 centerPoint)
{
    // get calculated position
    Vector3 newPosition = OrbitPosition(centerPoint, 10.0f, Random.Range(10.0f, 100.0f));
    // instantiate a new instance of GameObject
    GameObject newInstance = Instantiate(toInstantiate) as GameObject; 
    // check if instance was created
    if ( newInstance )
    {
        // set position to the newly created orbit position
        newInstance.transform.position = newPosition;
    }
    // return instance of the newly created object on correct position
    return newInstance;
}