I want to only place one duck (prefab) but the script I used is not function well because the raycast will also detect the AR Plane. However, for my objective I just want to
-tap and place a duck
-tap again the duck will show the confirmationUI.
-and also how should I code so that the UI canvas can nicely in front of the camera and also rotation by y-axis with 180 degree.
Here is the script for tap and place object and also show UI:
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Mouse clicked");
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
Debug.Log("Hit");
Debug.Log(hit.transform.name + " " + hit.transform.tag);
if (hit.collider.tag == "Placed Duck")
{
Debug.Log("Hit");
Debug.Log(hit.transform.name + " " + hit.transform.tag);
showUI();
return;
}
}
if (!isDuckSpawned && aRRaycastManager.Raycast(Input.mousePosition, hits, TrackableType.PlaneWithinPolygon))
{
foreach (ARRaycastHit ARhit in hits)
{
Debug.Log("Raycast produced");
if (aRPlaneManager.GetPlane(trackableId: ARhit.trackableId).alignment == PlaneAlignment.HorizontalUp)
{
Pose pose = ARhit.pose;
Debug.Log("Object placed");
if (spawnedObject == null)
{
Vector3 spawnDuckPosition = new Vector3 (pose.position.x, pose.position.y + 0.03f, pose.position.z);
spawnedObject = Instantiate(duck, spawnDuckPosition, pose.rotation);
spawnedObject.tag = "Placed Duck";
isDuckSpawned = true;
Debug.Log("Duck Spawned!");
break;
}
}
}
}
}
}
public void showUI()
{
Debug.Log("ShowConfirmationUI called");
if (canvas != null && confirmationUI != null)
{
Vector3 duckPosition = spawnedObject.transform.position;
Vector3 canvasPosition = new Vector3(duckPosition.x, duckPosition.y + 0.2f, duckPosition.z - 0.1f);
canvas.transform.position = canvasPosition;
canvas.transform.LookAt(Camera.main.transform);
confirmationUI.SetActive(true);
}
}