各种设备上的屏幕尺寸/比率灾难

时间:2016-02-23 15:05:06

标签: c# android unity3d

我从一两个月前开始用Unity3D制作游戏。我已经制作了我的第一款适用于Android的游戏,它在我的手机(三星Galaxy S6)和仿真器(使用不同的虚拟设备的Genymotion)上完美运行,但当我在父亲的手机上试用它时(Nexus 5,Xperia Z1& Z3)我意识到它工作不好。

游戏是2D汽车交通赛车,所以你必须躲避产卵者在X轴上随机位置创造的所有汽车。我不太了解Unity3d所以我无法更好地解释它,抱歉...... :(

问题是,在我的手机上,敌人的车辆从上到下正确地产卵,但是我父亲的手机正从中间到下方产生。另一个问题是当你将汽车向右或向左移动时,它看起来像是对角线切割。

这是enemys spawner的代码:

public class SpawnerEnemigos : MonoBehaviour {

public GameObject[] cochesEnemigos;
int cocheEnemigoID;
public float maxPos = 2f;
public float delayTimer = 0.5f;
private float timer;

// Use this for initialization
void Start () {
    timer = delayTimer;
}

// Update is called once per frame
void Update () {

    timer -= Time.deltaTime;
    if (timer <= 0) {
        Vector2 enemigoRandomPos = new Vector2 (Random.Range(-maxPos, maxPos), transform.position.y);
        cocheEnemigoID = Random.Range(0,7);
        Instantiate (cochesEnemigos[cocheEnemigoID], enemigoRandomPos, transform.rotation);
        timer = delayTimer;
    }
}

}

1 个答案:

答案 0 :(得分:0)

  

问题是,在我的手机上,敌人的车从上到下正确地产卵,但是我父亲的手机正从屏幕中间产生到底部。

正如Joe所说,这可能是由于视口差异造成的。具有不同宽高比的设备可以根据屏幕改变汽车产生点。

以下是有关如何使用视口计算对象将在世界中生成的位置的文档:Camera.ViewportToWorldPoint

// This is the part that we will be replacing.
Vector2 enemigoRandomPos = new Vector2 (Random.Range(-maxPos, maxPos), transform.position.y);

以下是根据您提供的代码进行操作的方法:

// Set the offset of the X axis first. This should be fairly similar for most devices,
// if you find issues with it apply the same logic as the Y axis.
var x = Random.Range(-maxPos, maxPos);
// Here is where the magic happens, ViewportToWorldPoint converts a number between 0 and 1 to
// an in-world number based on what the camera sees. In this specific situation I am telling it: to use 0f, 1f
// which roughly translates to "At the top of the screen, on the left corner". Then storing the Y value of the call.
var y = Camera.main.ViewportToWorldPoint(new Vector2(0f, 1f)).y;
// Now that we have the x and y values, we can simply create the enemigoRandomPos based on them.
var enemigoRandomPos = new Vector2(x, y);

您可以删除我的所有评论并改为整行:

var enemigoRandomPos = new Vector2(Random.Range(-maxPos, maxPos), Camera.main.ViewportToWorldPoint(new Vector2(0f, 1f)).y);

要记住以下几点:

  • 可能没有定义Camera.main,你需要找到相机的一个实例(这超出了这个问题的范围所以我会让你谷歌,如果你有问题,让我知道,我很乐意提供更多信息)
  • 在某些宽高比下,X位置会变得怪异,所以我建议你也考虑使用视口计算
  • 将这些值(Y和相机)存储在Start方法上会更有效,并且只有在宽高比更改或相机更改时才更改它们。这对旧设备的性能有所帮助。更多的家庭作业研究。 :)
  • 在解决此类问题时,使用显示问题的静态精灵(也称为不移动的东西)会很有用。我会在屏幕的所有角落+中心产生大约9个精灵,以便在调试过程中看到汽车会从哪里产生视觉辅助。
  • 当人们试图向您提供反馈时,在提问图形性质的问题时提供屏幕截图可以提供帮助,请考虑下次添加一些:D
  

另一个问题是,当你将汽车向右或向左移动时,它看起来像是对角线切割。

根据这个描述,它听起来像汽车精灵的三角形和背景精灵的某种剪裁问题。我建议根据摄像机的位置来回移动背景以避免剪切。