Search Unity

ARKit: Object not appear when i touch the screen

Discussion in 'Scripting' started by afyqahhs, Mar 20, 2019.

  1. afyqahhs

    afyqahhs

    Joined:
    Dec 7, 2018
    Posts:
    1
    Hi, i do follow ARKit tutorial from youtube. then i want one object only that appear when i touch the screen so i read the comment said that i can make it by adding some script in it. But when i add the new script it appear nothing when i touched the screen. There is no error when i run this code but it just not working.

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.XR.ARFoundation;
    using UnityEngine.Experimental.XR;
    using System;

    public class ARTapToPlaceObject : MonoBehaviour
    {
    public GameObject objectToPlace;
    public GameObject placementIndicator;

    private ARSessionOrigin arOrigin;
    private Pose placementPose;
    private bool placementPoseIsValid = false;
    private bool placementIsComplete = false;

    void Start()
    {
    arOrigin = FindObjectOfType<ARSessionOrigin>();
    }

    void Update()
    {
    UpdatePlacementPose();
    UpdatePlacementIndicator();


    //if (placementPoseIsValid && Input.touchCount < 0 || (Input.GetTouch(0)).phase != TouchPhase.Began)

    if (placementPoseIsValid && Input.touchCount < 0 && Input.GetTouch(0).phase == TouchPhase.Began)
    {
    PlaceObject();
    }
    }

    private void PlaceObject()
    {
    placementIsComplete = true;
    Instantiate(objectToPlace, placementPose.position, placementPose.rotation);
    }


    private void UpdatePlacementIndicator()
    {
    if (!placementIsComplete && placementPoseIsValid)
    {
    placementIndicator.SetActive(true);
    placementIndicator.transform.SetPositionAndRotation(placementPose.position, placementPose.rotation);
    }

    else
    {
    placementIndicator.SetActive(false);
    }
    }

    private void UpdatePlacementPose()
    {

    var screenCenter = Camera.current.ViewportToScreenPoint(new Vector3(0.5F, 0.5F));
    var hits = new List<ARRaycastHit>();
    arOrigin.Raycast(screenCenter, hits, TrackableType.Planes);

    placementPoseIsValid = hits.Count > 0;

    if (placementPoseIsValid)
    {


    placementPose = hits[0].pose;


    var cameraForward = Camera.current.transform.forward;
    var cameraBearing = new Vector3(cameraForward.x, 0, cameraForward.z).normalized;
    placementPose.rotation = Quaternion.LookRotation(cameraBearing);
    }

    }

    }



    Someone please help me fix this