I am trying to select a single/multiple objects and translating them using x,y,z coordinates panel. What I have done already is moving them to a specific coordinate, but not translating. In-order to translate them, I must get the current xyz coordinates of the selected objects and add to them the xyz coordinates which the user have written into the panel. Can anyone help me with this issue?
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();
}
}
CodePudding user response:
transform.position
contains the current position. so your update function would look like
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);
}
By the way, you don't need to Update the position all the time, you can use the events from the InputFields. Make a function like
public void PositionChanged(string newPos)
{
xPos = transform.position.x float.Parse(newPos);
}
and assign it in Unity:
CodePudding user response:
if you just want to add the vector instead of setting it then simply replace
target.transform.position = new Vector3(xPos, yPos, zPos);
by
// |
// V
target.transform.position = new Vector3(xPos, yPos, zPos);
or alternatively if it is easier to read for you use according method Transform.Translate
target.transform.Translate(new Vector3(xPos, yPos, zPos), Space.World);