You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity 2D游戏适配:如何按屏幕宽度动态生成适配的2D立方体?

解决Unity 2D中屏幕像素与世界单位不匹配的立方体生成问题

你猜得完全正确!问题的核心就是像素单位和世界单位的不匹配——Screen.width返回的是屏幕的像素总数,而Renderer.bounds.size.x是物体在Unity世界坐标系中的实际宽度,这俩直接相除肯定得不到正确的生成数量。咱一步步来解决这个问题:

核心思路:把屏幕像素范围转换成世界坐标范围

要计算能填满屏幕的立方体数量,首先得知道屏幕在世界坐标系中对应的宽度,而不是像素宽度。我们可以通过相机的ScreenToWorldPoint()方法完成这个转换。

调整后的完整代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class move : MonoBehaviour {
    public GameObject cubePrefab;
    public static bool spawn;
    int spawnCount;
    float objectSize;
    Camera mainCam;

    // Use this for initialization
    void Start() {
        spawn = true;
        mainCam = Camera.main;
        // 从预制体获取物体尺寸,比找场景对象更稳妥
        objectSize = cubePrefab.GetComponent<Renderer>().bounds.size.x;
        
        // 计算屏幕对应的世界宽度
        Vector3 leftWorldPos = mainCam.ScreenToWorldPoint(new Vector3(0, 0, mainCam.nearClipPlane));
        Vector3 rightWorldPos = mainCam.ScreenToWorldPoint(new Vector3(Screen.width, 0, mainCam.nearClipPlane));
        float worldScreenWidth = rightWorldPos.x - leftWorldPos.x;

        // 计算需要生成的立方体数量(向上取整确保填满屏幕)
        spawnCount = Mathf.CeilToInt(worldScreenWidth / objectSize);
    }

    // Update is called once per frame
    void Update() {
        if(spawn == true) {
            // 计算屏幕垂直中心的世界坐标(可以根据需求调整y位置)
            float centerY = mainCam.ScreenToWorldPoint(new Vector3(0, Screen.height/2, mainCam.nearClipPlane)).y;
            
            for(int i=0; i < spawnCount; i++) {
                // 从屏幕左边缘开始排列,每个立方体的中心位置对齐
                float xPos = mainCam.ScreenToWorldPoint(new Vector3(0, 0, mainCam.nearClipPlane)).x + objectSize/2 + i * objectSize;
                Vector3 pos = new Vector3(xPos, centerY, 0);
                Instantiate(cubePrefab, pos, transform.rotation);
            }
            spawn = false;
        }
    }
}

几个关键细节说明

  • 相机类型:确保你的相机是正交相机(2D游戏默认配置),如果用透视相机,屏幕边缘的世界坐标转换会有透视畸变,需要额外调整。
  • 物体尺寸获取:直接从预制体获取尺寸,避免依赖场景中特定名称的对象,代码更健壮。
  • 位置对齐:用objectSize/2来让立方体的中心对齐屏幕左边缘,避免物体一半在屏幕外的情况。
  • 数量取整:用Mathf.CeilToInt()向上取整,确保哪怕最后一个立方体只需要一部分也会生成,完全填满屏幕。

内容的提问来源于stack exchange,提问作者Keyx van Lierop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:47:36