首页 > 解决方案 > 从 ScreenToWorldPoint 转换给我错误的值

问题描述

GameObjects我使用以下代码通过脚本实例化一些:

for (int x = 0; x < data.game.Length; x++)
    for (int y = 0; y < data.game[x].LayerList.Length; y++)
    {
        int posX = data.game[x].LayerList[y].PositionOnMapX;
        int posY = data.game[x].LayerList[y].PositionOnMapY; 

        InsertWord(data.game[x].LayerList[y].Word, data.game[x].LayerList[y].Direction, posX, posY, boardHeight);
    }
}

private void InsertWord(string word, int direction, int positionX, int positionY, int boardHeight)
{

    int x = positionX;
    int y = boardHeight - positionY;

    for (int i = 0; i < word.Length; i++)
    {
        string letter = word.Substring(i, 1);
        tileText.text = letter;

        Vector2 tempPosition = new Vector2(x, y);

        /// Instantiate Background Tile
        GameObject backgroundTile = Instantiate(tilePrefab, tempPosition, Quaternion.identity, this.transform) as GameObject;
        backgroundTile.name = letter + " ( " + x + "," + y + ")";
        allTiles[x, y] = backgroundTile;

        if (direction == 0)
            x += 1;
        else
            y -= 1;
    }
}

对象已正确实例化。问题是它们是在屏幕视图坐标中实例化的,但我需要将它们转换为世界点,因为它们不在屏幕上。

我试图转换tempPosition为 WorldCoordinates: Vector3 screenVector = camera.ScreenToWorldPoint(new Vector3(x,y,10))

但所有实例化GameObjects的 X,Y,Z (2.3 , 5, 0) 都相同。

在此处输入图像描述

标签: unity3dcoordinates

解决方案


这是因为您从这里传递世界坐标:

int posX = data.game[x].LayerList[y].PositionOnMapX;

您应该最好将父游戏对象缩放到相机视图的中心。

您应该根据 X 中的最大图块和 Y 中的最大图块执行此操作,使其居中。

在此处输入图像描述

像这样,您的父对象需要移动和缩放。


推荐阅读