【问题标题】:Calling my background Sprite to fill screen in Unity在 Unity 中调用我的背景 Sprite 来填充屏幕
【发布时间】:2018-08-25 12:17:03
【问题描述】:

我知道网上有很多这样的问题,但我还没有找到解决我的问题的方法......

我正在尝试制作一个填满屏幕的背景图像。在我的游戏中,有一个画布,在这个画布内部有一个附加了精灵组件的游戏对象。

许多解决方案都包含此代码:

void Awake()
{
    SpriteRenderer sr = GetComponent<SpriteRenderer>();
    if (sr == null) return;

    transform.localScale = new Vector3(1, 1, 1);

    float width = sr.sprite.bounds.size.x;
    float height = sr.sprite.bounds.size.y;

    double variable = Camera.main.orthographicSize * 4.0;
    float worldScreenHeight = (float)variable;
    float worldScreenWidth = worldScreenHeight / Screen.height * Screen.width;

    transform.localScale = new Vector2(worldScreenWidth / width, worldScreenHeight / height);
}

但我试过了,它使游戏对象变得非常小。 有什么想法吗?

【问题讨论】:

  • 为什么不在画布内使用 UI Image 而不是 sprite?
  • 我试过这种方式,但我遇到了另一种问题:stackoverflow.com/questions/52016176/…
  • 好的;我编辑了您的代码,并将向您发布答案:)

标签: unity3d sprite screen-size gameobject


【解决方案1】:

首先,选择您的 Canvas 游戏对象。在Canvas Scaler 组件中将UI Scale Mode 设置为Constant Pixel Size

请注意,当您将UI Scale Mode 设置为Scale With Screen Size 时,您的图像会随屏幕宽度或高度而变化。

另外,请注意,您的图片应位于其父级的中心。将图像的变换位置和旋转设置为:

现在将您的代码更改为:

void Awake()
{
    SpriteRenderer sr = GetComponent<SpriteRenderer>();
    if (sr == null) return;

    transform.localScale = new Vector3(1, 1, 1);

    float width = sr.sprite.bounds.size.x;
    float height = sr.sprite.bounds.size.y;

    transform.localScale = new Vector2(Screen.width / width, Screen.height / height);
}

希望对你有帮助。

【讨论】:

  • 我认为现在完全是屏幕大小的一半:i.imgur.com/QAaKylC.png
  • 不,它不完全是一半,因为我试过这段代码:transform.localScale = new Vector2((Screen.width / width), Screen.height / height);并且图像没有填满屏幕
  • 有没有办法获取画布的宽高?
  • 图片现在满屏了吗?
  • 没问题我的朋友:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
  • 2015-01-10
  • 2021-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多