简体   繁体   English

为什么gameObject在Unity中获得这样的位置?

[英]Why gameObject get such positions in Unity?

I want to create 2d game. 我想创建2D游戏。 Structure of objects 对象的结构

在此处输入图片说明 [] []

"View" present a square where everything happens. “视图”提供了发生一切的正方形。

"Initial" This is the same square with a mask “初始”,这是与面具相同的正方形

"SquareList" is empty panel. “ SquareList”是空白面板。

Why am I doing this? 我为什么要这样做?

I created a script where when I click on the screen, a new square is added to the SquareList. 我创建了一个脚本,在其中单击屏幕时,会将一个新的正方形添加到SquareList中。 SquareList is the parent. SquareList是父级。 I created a script to determine the position of the cursor. 我创建了一个脚本来确定光标的位置。

createPos = new Vector2 (Input.mousePosition.x, Input.mousePosition.y);

Next, I want to set for new object position = cursor position. 接下来,我要设置新的对象位置=光标位置。

Cursor.position equivalent = (562,1134 / 242.6486) But the new object get position (94931.29 / 103365.6 / -17280) 等效于Cursor.position =(562,1134 / 242.6486)但新对象获得位置(94931.29 / 103365.6 / -17280)

But if I set position of new object to = new Vector(0,0); 但是如果我将新对象的位置设置为= new Vector(0,0); Then everything is fine 那一切都很好

What is the problem? 问题是什么?

Input.mousePosition returns position in pixel-coordinate. Input.mousePosition返回像素坐标中的位置。 You have to use Camera.main.ScreenToWorldPoint to convert it to world position then assign that to the object. 您必须使用Camera.main.ScreenToWorldPoint将其转换为世界位置,然后将其分配给对象。 If 3D Object, add an offset to it before converting with ScreenToWorldPoint . 如果是3D对象,请在使用ScreenToWorldPoint进行转换之前ScreenToWorldPoint添加偏移量。

public GameObject prefab;
public float offset = 10f;

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Vector3 clickPos;

        clickPos = Input.mousePosition;
        clickPos.z = offset;

        clickPos = Camera.main.ScreenToWorldPoint(clickPos);
        GameObject obj = Instantiate(prefab, clickPos, Quaternion.identity);
    }
}

Hello nameless brother/sister! 你好,无名兄弟姐妹! I believe you are seeing this issue because your game object's coordinates are affected by its parent's coordinates. 我相信您会看到此问题,因为游戏对象的坐标受其父对象的坐标影响。 You may need to use localPosition to find more relative coordinates. 您可能需要使用localPosition查找更多相对坐标。

More info: https://docs.unity3d.com/ScriptReference/Transform-localPosition.html 更多信息: https : //docs.unity3d.com/ScriptReference/Transform-localPosition.html

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

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