选择 single/multiple 个对象并使用 Unity 中的坐标移动它们

Selecting a single/multiple Objects and moving them using coordinates in Unity

我正在尝试 select 一个 single/multiple 对象并使用 x,y,z 坐标面板转换它们。我已经做的是将它们移动到一个特定的坐标,而不是平移。为了翻译它们,我必须获取 selected 对象的当前 xyz 坐标,并将用户写入面板的 xyz 坐标添加到它们中。谁能帮我解决这个问题?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using TMPro;

public class InstantiateWithButton : MonoBehaviour
{

public GameObject[] prefabs = null;
public Camera cam = null;

public GameObject XYZPanel;

// public Vector3 newposition;

public float xPos;
public float yPos;
public float zPos;

public TMP_InputField inputx;
public TMP_InputField inputy;
public TMP_InputField inputz;

public GameObject target;

public List<GameObject> targets = new List<GameObject> ();


void Start()
{
    XYZPanel.SetActive(false);
    inputx.text = 0.0f.ToString();
    inputy.text = 0.0f.ToString();
    inputz.text = 0.0f.ToString();

}

void Update()
{
    InstantiateObject();

    xPos = float.Parse(inputx.text);
    yPos = float.Parse(inputy.text);
    zPos = float.Parse(inputz.text);

}

public void InstantiateObject()
{
    if(!EventSystem.current.IsPointerOverGameObject())
    {
        if(Input.GetMouseButtonDown(2))
        {
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if(Physics.Raycast(ray, out hit))
        {
            if(hit.collider.gameObject.tag == "atom")
            {
                Instantiate(target, hit.point, Quaternion.identity);
            }
            if(hit.collider.gameObject.tag == "Object")
            {
                XYZPanel.SetActive(true);
                targets.Add(hit.collider.gameObject);
            }
        }

        }   
    }

}


public void moveObject()
{

    foreach(var target in targets)
    {
        target.transform.position = new Vector3(xPos, yPos, zPos);
    }
    targets.Clear();
}





}

transform.position 包含当前位置。所以你的更新函数看起来像

void Update()
{
    InstantiateObject();

    xPos = transform.position.x + float.Parse(inputx.text);
    yPos = transform.position.y + float.Parse(inputy.text);
    zPos = transform.position.z + float.Parse(inputz.text);
}

顺便说一句,您不需要一直更新位置,您可以使用来自 InputFields 的事件。 做一个像

这样的函数
public void PositionChanged(string newPos)
{
    xPos = transform.position.x + float.Parse(newPos);
}

并在 Unity 中赋值:

如果您只是想 添加 向量而不是设置它,那么只需替换

target.transform.position = new Vector3(xPos, yPos, zPos);

来自

//                        |
//                        V
target.transform.position += new Vector3(xPos, yPos, zPos);

或者如果您更容易阅读,请使用方法 Transform.Translate

target.transform.Translate(new Vector3(xPos, yPos, zPos), Space.World);

如果你更希望下摆全部根据 local space 独立移动,那么最好使用

target.transform.localPosition += new Vector3(xPos, yPos, zPos);

或相应地

target.transform.Translate(new Vector3(xPos, yPos, zPos));