[英]Selecting a single/multiple Objects and moving them using coordinates in Unity
我正在尝试 select 单个/多个对象并使用 x、y、z 坐标面板转换它们。 我已经做的是将它们移动到一个特定的坐标,而不是平移。 为了翻译它们,我必须获取所选对象的当前 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
包含当前的 position。因此您的更新 function 看起来像
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);
}
顺便说一下,您不需要一直更新 position,您可以使用 InputFields 中的事件。 制作一个 function 赞
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);
如果您更希望下摆全部在其相应的本地空间中独立移动,那么请使用
target.transform.localPosition += new Vector3(xPos, yPos, zPos);
或相应地
target.transform.Translate(new Vector3(xPos, yPos, zPos));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.