简体   繁体   English

如何统一获得相机宽度

[英]how to get camera width in unity

Problem 问题

I have a spawn manager written in c# which spawns my game object, i use screen.width, to set the maximum screen with and -screen.width to set the minimum screen width for the spawning, but my game object spawns way off the screen. 我有一个用C#编写的生成器管理器,它生成我的游戏对象,我使用screen.width来设置最大屏幕,使用-screen.width来设置生成的最小屏幕宽度,但是我的游戏对象的生成距离屏幕很远。

I am using a portrait camera 2:3 instead of free aspect as my camera view, as i want my game to be in portrait mode 我使用人像摄影机2:3而不是自由宽高比作为我的摄影机视图,因为我希望游戏处于人像模式

how do i make my game object spawn within the camera widths(max and min)? 如何使我的游戏对象在相机宽度(最大和最小)范围内产生?

my code 我的密码

public class SpawnManager : MonoBehaviour {

    public int maxBalloons = 100;
    public GameObject balloon;
    public float horizontalMin = -Screen.width;
    public float horizontalMax = Screen.width;
    public float verticalMin = -5.0f;
    public float verticalMax = 1.0f;


    private Vector2 originPosition;


    void Start () {

        originPosition = transform.position;
        Spawn ();

    }

    void Spawn()
    {
        for (int i = 0; i < maxBalloons; i++)
        {
            Vector2 randomPosition = originPosition + new Vector2 (Random.Range(horizontalMin, horizontalMax), Random.Range (verticalMin, verticalMax));

            Instantiate(balloon, randomPosition, Quaternion.identity);
            originPosition = randomPosition;
        }
    }

}

Edit I changed 编辑我改变了

Vector2 randomPosition = originPosition + new Vector2 (Random.Range(horizontalMin, horizontalMax), Random.Range (verticalMin, verticalMax));

To

Vector2 randomPosition =Camera.ScreenToWorldPoint (originPosition + new Vector2 (Random.Range(horizontalMin, horizontalMax), Random.Range (verticalMin, verticalMax)));

Still did not work as it should 仍然无法正常工作

A position on your screen with a X smaller than 0 will be always out of your screen. X小于0的位置在屏幕上总是会出现在屏幕之外。 The bottom left corner of your screen is the origin of your the coordinate (x: 0, y: 0) 屏幕的左下角是坐标的原点(x:0,y:0)

But here I think you mingled 2 kinds of positions. 但是在这里我认为您混合了两种职位。 The position on your screen, is not the same position in the world space of your scene. 屏幕上的位置与场景的世界空间中的位置不同。 It depends where the camera is rendering. 这取决于相机在哪里渲染。 The position on the bottom left corner of your screen will not be x:0 y:0 in the world space. 屏幕左下角的位置在世界空间中将不会是x:0 y:0。

To achieve what you are looking for you need to transform the position on the left and the right of your camera into worldspace positions. 为了实现所需的功能,您需要将相机左右两侧的位置转换为世界空间位置。

Use Camera.ScreenToWorldPoint to achieve that : https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html 使用Camera.ScreenToWorldPoint实现以下目的: https ://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM