- Home /
Vuforia, how to spawn a prefab on target image and not above?
Hello all,
I'm building an AR scene with Vuforia image target. Once I touch the image target the prefab appears but it looks "hanging" in the air. I'd like the prefab to appear as if it is "standing" on the target image, namely so that the prefabs' and the images' y coordinate is the same.
this is my code in C#:
using UnityEngine;
public class SpawnSystem : MonoBehaviour
{
public Transform targetObject;
public Transform targetPlane;
//float distance = 10f;
Animator anim;
private void Awake()
{
anim = GetComponentInChildren<Animator>();
}
private void Update()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
Vector3 fingerPos = Input.GetTouch(0).position;
//fingerPos.z = 5;
Vector3 objPos = Camera.main.ScreenToWorldPoint(new Vector3 (fingerPos.x, fingerPos.y, fingerPos.z));
targetObject.position = objPos;
Instantiate(targetObject, targetObject.position, targetObject.transform.rotation, targetPlane);
}
}
}
The issue you're having is very common and has been asked / answered quite a bit.
https://docs.unity3d.com/ScriptReference/Transform-position.html
You can't modify position like that because fields of a struct cannot be directly modified. You have to create a new Vector3 instance, assign the x/y/z components, then reassign the objects position entirely.
Hi @TreyH I've managed to solve this for a while partially... but it still not working. I've reassigned the position:
public Transform towerPrefabClone;
public GameObject towerPrefab;
float floorHeight = 0f;
void Update()
{
for (int i = 0; i < Input.touchCount; i++)
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
Vector3 fingerPos = Input.GetTouch(0).position;
fingerPos.z = 5;
Vector3 objPos = Camera.main.ScreenToWorldPoint(fingerPos);
towerPrefabClone = (Instantiate(towerPrefab, objPos, Quaternion.identity) as GameObject).transform;
Vector3 groundPos = new Vector3 (objPos.x, floorHeight, objPos.z);
if (towerPrefabClone.position.y > floorHeight)
{
towerPrefabClone.position = groundPos;
towerPrefabClone.GetComponent<Animator>().SetBool("RisingAbove", true);
}
}
}
At first y was zero, but now it's not working.
Answer by Eco-Editor · May 09, 2018 at 03:19 PM
I've solved this by searching further here's the best solution: https://developer.vuforia.com/forum/general-discussion/getting-object-touch-position
Your answer
Follow this Question
Related Questions
Give prefab a parent 2 Answers
How can I make an in-game search engine similar to Scribblenauts 1 Answer
i need to destroy prefab clones 1 Answer