精灵自动定位和缩放

时间:2018-10-13 04:30:34

标签: c# unity3d

我有4个带有碰撞器的子画面,我想自动将它们定位并按比例缩放到屏幕底部,这样它们就不会越过圈并且完全不在屏幕外。我不能在画布上做到这一点,它需要作为gameObjects完成。

我还试图根据其外观将每个Sprits高度设置为1 / 4th-1 / 5th,这就是为什么下面将代码除以4的原因。

如何使它们并排放置在底部?

public class AutoPosition : MonoBehaviour {

public Sprite [] goals;

public float width = Screen.width / 4;
public float height = Screen.height / 4;
// Use this for initialization
void Start () {
    for (int i = 0; i < goals.Length; i++) {
        goals[i]
    }
}

1 个答案:

答案 0 :(得分:1)

您可以对图像使用SpriteRender。并将它们放在父GameObject中。仅简单地正确缩放和定位一个父项GameObject(与画布类似,但具有常规的Transform组件)就足够了。

public class applySize : MonoBehaviour 
{
    private void Apply()
    {
        // Get the main camera position
        var cameraPosition = Camera.main.transform.position;

        // This makes the parent GameObject "fit the screen size"
        float height;
        if (Camera.main.orthographic)
        {
            // Camera projection is orthographic
            height = 2 * Camera.main.orthographicSize;
        }
        else
        {
            // Camera projection is perspective
            height = 2 * Mathf.Tan(0.5f * Camera.main.fieldOfView * Mathf.Deg2Rad) * Mathf.Abs(cameraPosition.z - transform.position.z);
        }

        var width = height * Camera.main.aspect;

        transform.localScale = new Vector3(width, height,1);
        transform.position = cameraPosition - new Vector3(0,height*.375f, cameraPosition.z);

        // Since the 4 images are childs of the parent GameObject there is no need
        // place or scale them separate. It is all done with placing this parent object
    }

    private void Start()
    {
        Apply();
    }
}

使用以下场景设置

enter image description here

精灵的X位置只是

  • 图片1:-宽度* 1.5;
  • image2:-宽度* 0.5;
  • image3:宽度* 0.5;
  • image4:宽度* 1.5;

以及四个SpriteRenderers

enter image description here

和对撞机

enter image description here

结果

(在Update中有一个附加呼叫)

enter image description here

我将父级职位保留在Z = 0上。您可以根据需要进行更改。 这样,对撞机现在应该可以与其他对象进行交互了。

相关问题