从ScreenToWorldPoint转换给我错误的值

时间:2019-07-31 11:12:18

标签: unity3d coordinates

我使用以下代码通过脚本实例化一些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;
    }
}

对象已正​​确实例化。问题在于它们是在“屏幕视图”坐标中实例化的,但是我需要将它们转换为World Point,因为它们不在屏幕上。

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

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

enter image description here

1 个答案:

答案 0 :(得分:0)

这是因为您要从此处传递世界坐标:

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

您最好将父级GameObject缩放到摄像机视图的中心。

您应该基于X中的最大图块和Y中的最大图块来做到这一点。

enter image description here

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