void ProcessInput() { if (Input.touchCount > 0 && buttonPressed == false) { var touch = Input.GetTouch(0); if (touch.tapCount == 2) { currentAnimation = AnimState.Dance; return; } if (touch.phase == TouchPhase.Began) { var screenPosition = Camera.main.ScreenToViewportPoint(touch.position); ARPoint point = new ARPoint { x = screenPosition.x, y = screenPosition.y }; List <ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest( point, ARHitTestResultType.ARHitTestResultTypeEstimatedHorizontalPlane); if (hitResults.Count > 0) { foreach (var hitResult in hitResults) { Vector3 position = UnityARMatrixOps.GetPosition(hitResult.worldTransform); PetGo(position); break; } } } } }
bool HitTestWithResultType(ARPoint point, ARHitTestResultType resultTypes) { if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) { return(false); } // don't register touches on the UI List <ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, resultTypes); if (hitResults.Count > 0) { foreach (var hitResult in hitResults) // Why not just get [0] instead of looping? { m_HitTransform.position = UnityARMatrixOps.GetPosition(hitResult.worldTransform) + Vector3.up * 0.02f; // move above grid slightly m_HitTransform.rotation = UnityARMatrixOps.GetRotation(hitResult.worldTransform); if (!planePainting) { PaintPlaneOn(); } return(true); } } return(false); // no hit results }
public void UpdateEnvironmentProbe(AREnvironmentProbeAnchor environmentProbeAnchor) { transform.position = UnityARMatrixOps.GetPosition(environmentProbeAnchor.transform); Quaternion rot = UnityARMatrixOps.GetRotation(environmentProbeAnchor.transform); //rot.z = -rot.z; //rot.w = -rot.w; transform.rotation = rot; if (reflectionProbe != null) { reflectionProbe.size = environmentProbeAnchor.Extent; } if (debugExtentGO != null) { debugExtentGO.transform.localScale = environmentProbeAnchor.Extent; } latchedTexture = environmentProbeAnchor.Cubemap; latchUpdate = true; }
void UpdateImageAnchor(ARImageAnchor arImageAnchor) { Debug.Log("image anchor updated"); if (arImageAnchor.referenceImageName == referenceImage.imageName) { imageAnchorGO.transform.position = UnityARMatrixOps.GetPosition(arImageAnchor.transform); imageAnchorGO.transform.rotation = UnityARMatrixOps.GetRotation(arImageAnchor.transform); searchcount++; if (!issetparent && searchcount > searchlimit) { issetparent = true; offset = worldroot.position - imageAnchorGO.transform.position; eulerangleYoffset = worldroot.eulerAngles.y - imageAnchorGO.transform.eulerAngles.y; lockedDoneTitle.gameObject.SetActive(true); Debug.Log("记录初始偏移 == " + offset.ToString() + " " + eulerangleYoffset.ToString()); } else if (issetparent) { Debug.Log("位置恢复!!!!!!"); worldroot.position = imageAnchorGO.transform.position + offset; worldroot.eulerAngles = new Vector3(0, imageAnchorGO.transform.eulerAngles.y + eulerangleYoffset, 0); } } }
private void AddImageAnchor(ARImageAnchor arImageAnchor) { Debug.LogFormat("image anchor added[{0}] : tracked => {1}", arImageAnchor.Identifier, arImageAnchor.IsTracked); if (arImageAnchor.ReferenceImageName == "dynamicImage") { Vector3 position = UnityARMatrixOps.GetPosition(arImageAnchor.Transform); Quaternion rotation = UnityARMatrixOps.GetRotation(arImageAnchor.Transform); var arObjectState = ArBehaviour.ArObjectState; if (arObjectState != null && TriggerObject != null && !_gameObjectCreated) { _gameObjectCreated = true; lock (arObjectState) { transform.position = position; transform.rotation = rotation; var result = ArBehaviour.CreateArObject( arObjectState, TriggerObject.gameObject, null, transform, TriggerObject.poi, TriggerObject.poi.id, out _gameObject ); if (!ArBehaviourPosition.IsEmpty(result)) { ArBehaviour.ErrorMessage = result; return; } } } } }
void Update() { if (m_camera != null) { Matrix4x4 matrix = m_session.GetCameraPose(); Vector3 arPos = UnityARMatrixOps.GetPosition(matrix); Vector3 diff = arPos - lastArPos; Vector3 correctedDiff = new Vector3( sin * diff.z + cos * diff.x, diff.y, cos * diff.z - sin * diff.x); m_camera.transform.localPosition += correctedDiff; lastArPos = arPos; Quaternion r = UnityARMatrixOps.GetRotation(matrix); m_camera.transform.localRotation = Quaternion.Euler( r.eulerAngles.x, r.eulerAngles.y + initRotation.eulerAngles.y, r.eulerAngles.z); m_camera.projectionMatrix = m_session.GetCameraProjection(); } }
//testing //finding the place to place bool HitTestWithResultType(ARPoint point, ARHitTestResultType resultTypes) { List <ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, resultTypes); if (hitResults.Count > 0) { foreach (var hitResult in hitResults) { for (int i = 0; i < arpags.Count; i++) { if (hitResult.anchorIdentifier == arpags[i].planeAnchor.identifier) { selectedPlaneValue = i; // planePlacementState = planeState.Set; // print(planePlacementState); PlaceFloorPlane(UnityARMatrixOps.GetPosition(hitResult.worldTransform)); return(true); } } } } return(false); }
private bool HitTestWithResultType(ARPoint point, ARHitTestResultType resultType) { List <ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, resultType); if (hitResults.Count > 0) { foreach (ARHitTestResult hitResult in hitResults) { Debug.Log("Got hit!"); Vector3 position = UnityARMatrixOps.GetPosition(hitResult.worldTransform); Quaternion rotation = UnityARMatrixOps.GetRotation(hitResult.worldTransform); // Transform to placenote frame of reference Matrix4x4 worldTransform = Matrix4x4.TRS(position, rotation, Vector3.one); Matrix4x4?placenoteTransform = LibPlacenote.Instance.ProcessPose(worldTransform); Vector3 hitPosition = PNUtility.MatrixOps.GetPosition(placenoteTransform.Value); Quaternion hitRotation = PNUtility.MatrixOps.GetRotation(placenoteTransform.Value); // Create node info object NodeInfo nodeInfo = new NodeInfo(); nodeInfo.px = hitPosition.x; nodeInfo.py = hitPosition.y; nodeInfo.pz = hitPosition.z; nodeInfo.nodeType = (int)m_NodeController._selectedNodeType; m_NodeController.AddActiveNode(nodeInfo); return(true); } } return(false); }
void UpdateImageAnchor(ARImageAnchor arImageAnchor) { Debug.LogFormat("image anchor updated[{0}] : tracked => {1}", arImageAnchor.identifier, arImageAnchor.isTracked); if (bindObjectToImage && arImageAnchor.referenceImageName == referenceImage.imageName) { if (arImageAnchor.isTracked) { if (!imageAnchorGO.activeSelf) { imageAnchorGO.SetActive(true); } if (bindObjectToImage) { imageAnchorGO.transform.position = UnityARMatrixOps.GetPosition(arImageAnchor.transform); imageAnchorGO.transform.rotation = UnityARMatrixOps.GetRotation(arImageAnchor.transform); } } else if (destroyObjectOnEnd && imageAnchorGO) { GameObject.Destroy(imageAnchorGO); } } }
void FaceAdded(ARFaceAnchor anchorData) { anchorPrefab.transform.position = UnityARMatrixOps.GetPosition(anchorData.transform); anchorPrefab.transform.rotation = UnityARMatrixOps.GetRotation(anchorData.transform); anchorPrefab.SetActive(true); }
void Update() { if (m_camera != null && sessionStarted) { // Positional information of AR camera Matrix4x4 matrix = m_session.GetCameraPose(); Vector3 newPos = UnityARMatrixOps.GetPosition(matrix); passedTime += Time.deltaTime; // Get accelerometer difference (experimental) double acc = Input.acceleration.z - lastAcc.z; //Changed from Float to double on 6 Apr to try and get Acc data to show if (acc > 0) { dir = Direction.backward; } else if (acc < 0) { dir = Direction.forward; } // Do speed calculation and update UI if (frames % speedFrames == 0) { double dist = Vector3.Distance(newPos, lastPos); //Changed from Float to double on 6 Apr to try and get Acc data to show | Added 6 Apr speed = dist / passedTime; speedText.text = "Speed " + speed.ToString(); if (speed > 1) { warningText.text = "Slow down!"; if (dir == Direction.forward) { directionText.text = "Forwards"; } else { directionText.text = "Backwards"; } } else { warningText.text = ""; directionText.text = ""; } // Reset counters and update last recorded info frames = 0; passedTime = 0; lastPos = m_camera.transform.localPosition; lastAcc = Input.acceleration; // Debug text posText.text = "Pos: " + m_camera.transform.localPosition; accText.text = "Acc: " + (string.Format("{0:0.000000000000}", (Input.acceleration - lastAcc))); //Ensure it's formatting value to 12 places after the decimal point so that it's clear whether there's any value in there. debugAccText.text = "Acc Debug: " + (Input.acceleration); //Display Current Acceleration to debug the Acceleration bug: Added 6 Apr debugAccTypeText.text = "Acc Type: " + (Input.acceleration.GetType()); //Added 6 Apr: Should Display type of the Input.accleration val to determine if it's an int } frames++; // Move game camera to new position/rotation sensed m_camera.transform.localPosition = UnityARMatrixOps.GetPosition(matrix); m_camera.transform.localRotation = UnityARMatrixOps.GetRotation(matrix); m_camera.projectionMatrix = m_session.GetCameraProjection(); } }
void HitTest(ARPoint arPoint) { List <ARHitTestResult> hitResults = UnityARSessionNativeInterface .GetARSessionNativeInterface() .HitTest(arPoint, ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent); // ロボットを検出するオブジェクトと検出したオブジェクトにPrefabを重ねて表示するオブジェクト GameObject generateObjectAnchor = GameObject.Find("GenerateObjectAnchor"); GameObject objectAnchorGO = generateObjectAnchor.GetComponent <GenerateRobotAnchor>().objectAnchorGO; // 平面とあたっている かつ ロボットを検出している場合 if (hitResults.Count > 0 && objectAnchorGO != null) { // 1回目のタッチ if (!isPlaced) { // 前回指定したゴール位置を削除 Destroy(goalPosition); Destroy(goalRotation); goalPosition = Instantiate(goalPositionPrefab); goalPosition.transform.position = UnityARMatrixOps.GetPosition(hitResults[0].worldTransform); goalPosition.transform.rotation = UnityARMatrixOps.GetRotation(hitResults[0].worldTransform); this.isPlaced = true; } // 2回目のタッチ else { goalRotation = Instantiate(goalRotationPrefab); // 1回目にタッチした位置に対する、2回目にタッチした位置の方向を計算 Vector3 p1 = goalPosition.transform.position; Vector3 p2 = UnityARMatrixOps.GetPosition(hitResults[0].worldTransform); Vector3 d = p2 - p1; float rad = Mathf.Atan2(d.z, d.x); float degree = rad * Mathf.Rad2Deg; // 上で計算した方向に三角を向けて配置 goalRotation.transform.position = p1; goalRotation.transform.localEulerAngles = new Vector3(0, -degree, 0); // Websocketがつながっている // Goal位置をPublishする if (RBSocket.Instance.IsConnected) { //////// ロボット座標系でのゴールの位置・姿勢を計算 //////// // Unity座標系で見たロボットとゴールの相対位置 Vector3 robo2Goal = goalPosition.transform.position - objectAnchorGO.transform.position; float dx = robo2Goal.x; float dz = robo2Goal.z; // ロボット座標系でのゴールの位置 UnityEngine.Quaternion robotQua = objectAnchorGO.transform.rotation; float theta = -robotQua.eulerAngles.y * Mathf.Deg2Rad; // 左ねじ回転なのでマイナス Vector3 rGoalPosition = new Vector3(dx * Mathf.Cos(-theta) - dz * Mathf.Sin(-theta), 0, dx * Mathf.Sin(-theta) + dz * Mathf.Cos(-theta)); // ロボット座標系でのゴールの姿勢 UnityEngine.Quaternion goalQua = goalRotation.transform.rotation; UnityEngine.Quaternion rGoalRotation = goalQua * UnityEngine.Quaternion.Inverse(robotQua); // 垂直z右手座標系に変換 UnityEngine.Quaternion rosGoalRotation = UnityEngine.Quaternion.Euler(0, 0, -rGoalRotation.eulerAngles.y); ///////// ROS のメッセージ送信 ///////// // PoseStamped (Header, Pose) RBS.Messages.geometry_msgs.PoseStamped msg = new RBS.Messages.geometry_msgs.PoseStamped(); // Header RBS.Messages.std_msgs.Header header = new RBS.Messages.std_msgs.Header(); header.frame_id = "base_footprint"; msg.header = header; // msg.header.frame_id = "base_footprint"; // Pose RBS.Messages.geometry_msgs.Pose pose = new RBS.Messages.geometry_msgs.Pose(); // position RBS.Messages.geometry_msgs.Point position = new RBS.Messages.geometry_msgs.Point(); position.x = rGoalPosition.x; position.y = rGoalPosition.z; position.z = 0; pose.position = position; // orientation RBS.Messages.geometry_msgs.Quaternion orientation = new RBS.Messages.geometry_msgs.Quaternion(); orientation.x = rosGoalRotation.x; orientation.y = rosGoalRotation.y; orientation.z = rosGoalRotation.z; orientation.w = rosGoalRotation.w; pose.orientation = orientation; msg.pose = pose; goalPub.publish(msg); } this.isPlaced = false; } } }
// Please import Unity ARKit Plugin if you are seeing a compiler error here. void UpdateMapPositionWithAnchor(ARPlaneAnchor arPlaneAnchor) { //Setting the position of our map to match the position of anchor wrldMapParent.position = UnityARMatrixOps.GetPosition(arPlaneAnchor.transform); }
protected override void FaceAdded(ARFaceAnchor anchorData) { currentBlendShapes = anchorData.blendShapes; model.transform.localPosition = UnityARMatrixOps.GetPosition(anchorData.transform) + offset; prevRotation = UnityARMatrixOps.GetRotation(anchorData.transform).eulerAngles; }
public static Vector3 GetPosition(ARPlaneAnchor planeAnchor) { return(UnityARMatrixOps.GetPosition(planeAnchor.transform)); }
// Update is called once per frame void Update() { remainingFlowers = gardenController.GetComponent <gardenController>().gardenFlowers - currentFlower + 1; beesCreated.text = gardenController.GetComponent <gardenController>().gardenBees - beeStack.Count + " bees fed"; beesRemaining.text = beeStack.Count + " bees left"; /* * if (popUp.IsActive()==true){ * // * Debug.Log("popup active? "+popUp.IsActive()); * } */ //Debug.Log("popup active? "+popUp.IsActive()); #if UNITY_EDITOR //we will only use this script on the editor side, though there is nothing that would prevent it from working on device if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; //we'll try to hit one of the plane collider gameobjects that were generated by the plugin //effectively similar to calling HitTest with ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent if (Physics.Raycast(ray, out hit, maxRayDistance, collisionLayer)) { //CreateBall (new Vector3 (hit.point.x, hit.point.y + createHeight, hit.point.z),); //we're going to get the position from the contact point Debug.Log(string.Format("x:{0:0.######} y:{1:0.######} z:{2:0.######}", hit.point.x, hit.point.y, hit.point.z)); } } #else if (Input.touchCount > 0) { var touch = Input.GetTouch(0); if (touch.phase == TouchPhase.Began) { var screenPosition = Camera.main.ScreenToViewportPoint(touch.position); ARPoint point = new ARPoint { x = screenPosition.x, y = screenPosition.y }; List <ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent); if (hitResults.Count > 0) { foreach (var hitResult in hitResults) { Vector3 position = UnityARMatrixOps.GetPosition(hitResult.worldTransform); //add createheight to the y below placeLevel = new Vector3(position.x, createHeight, position.z); Vector3 flowerLevel = new Vector3(placeLevel.x, 0, placeLevel.z); flowerNum.text = remainingFlowers + " flowers left"; if (totalBees != 0 && popUp.IsActive() == false && currentFlower < remainingFlowers) { alert.SetActive(false); CreateBall(flowerLevel, twoFlower); currentFlower++; Debug.Log("current flower: " + currentFlower + ", total bees: " + totalBees + ", remaining flowers: " + remainingFlowers); } else if (totalBees == 0 && popUp.IsActive() == false) { // //alert.GetComponentInChildren<Text>().text = "You fed all the bees!"; Debug.Log("SCENE RESET"); SceneManager.LoadScene("Garden"); } else if (keeper.Instance.currentGardenLevel == 4) { // SceneManager.LoadScene("Beez"); } else { Debug.Log("TRY AGAIN"); } break; } } } } #endif }
void HitTest(ARPoint arPoint) { List <ARHitTestResult> hitResults = UnityARSessionNativeInterface .GetARSessionNativeInterface() .HitTest(arPoint, ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent); // ロボットを検出するオブジェクトと検出したオブジェクトにPrefabを重ねて表示するオブジェクト GameObject generateRobotAnchor = GameObject.Find("GenerateRobotAnchor"); GameObject robotAnchorGO = generateRobotAnchor.GetComponent <GenerateRobotAnchor>().objectAnchorGO; // 平面とあたっている かつ ロボットを検出している場合 if (hitResults.Count > 0 && robotAnchorGO != null) { // 1回目のタッチ if (!isPlaced) { // 前回指定したゴール位置を削除 Destroy(goalPosition); Destroy(goalRotation); goalPosition = Instantiate(goalPositionPrefab); goalPosition.transform.position = UnityARMatrixOps.GetPosition(hitResults[0].worldTransform); goalPosition.transform.rotation = UnityARMatrixOps.GetRotation(hitResults[0].worldTransform); this.isPlaced = true; } // 2回目のタッチ else { goalRotation = Instantiate(goalRotationPrefab); // 1回目にタッチした位置に対する、2回目にタッチした位置の方向を計算 Vector3 goalVec = goalPosition.transform.position; Vector3 hitVec = UnityARMatrixOps.GetPosition(hitResults[0].worldTransform); Quaternion goalQua = Quaternion.LookRotation(hitVec - goalVec); goalRotation.transform.position = goalVec; goalRotation.transform.rotation = goalQua; // y軸成分以外の回転を除去 Vector3 goalEuler = goalQua.eulerAngles; goalQua = Quaternion.Euler(0, goalEuler.y, 0); // Websocketがつながっている // Goal位置をPublishする if (RBSocket.Instance.IsConnected) { ///////// ROS のメッセージ送信 ///////// // PoseStamped (Header, Pose) RBS.Messages.geometry_msgs.PoseStamped msg = new RBS.Messages.geometry_msgs.PoseStamped(); // Header RBS.Messages.std_msgs.Header header = new RBS.Messages.std_msgs.Header(); //header.frame_id = "base_footprint"; header.frame_id = "unity"; msg.header = header; // Pose RBS.Messages.geometry_msgs.Pose pose = new RBS.Messages.geometry_msgs.Pose(); // position RBS.Messages.geometry_msgs.Point position = new RBS.Messages.geometry_msgs.Point(); position.x = goalVec.z; position.y = -goalVec.x; position.z = 0; pose.position = position; // orientation RBS.Messages.geometry_msgs.Quaternion orientation = new RBS.Messages.geometry_msgs.Quaternion(); orientation.x = goalQua.z; orientation.y = -goalQua.x; orientation.z = goalQua.y; orientation.w = -goalQua.w; pose.orientation = orientation; msg.pose = pose; goalPub.publish(msg); } this.isPlaced = false; } } }
// Update is called once per frame void Update() { //CheckButton(); //Debug.Log("模型ActiveFalse"); if (Model.activeSelf == false) { if (Input.GetMouseButtonDown(0)) { var touch = Input.GetTouch(0); if (touch.phase == TouchPhase.Began) { //Debug.Log("执行HitTest"); Vector3 screenPos = Camera.main.ScreenToViewportPoint(touch.position); ARPoint point = new ARPoint { x = screenPos.x, y = screenPos.y }; List <ARHitTestResult> hitTestResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, ARHitTestResultType.ARHitTestResultTypeExistingPlane); if (flag == false && hitTestResults.Count > 0) { UnityARCameraManager.CloseDetection(); flag = true; GeneratePlane.GetComponent <FocusSquare>().enabled = false; FocusSquare.SetActive(false); HintController.ShowElement(3); } /* == 第一次点击的时候关闭平面检测 */ //Debug.Log("放置模型"); /* UNET */ var player = ClientScene.localPlayers[0].gameObject.GetComponent <Player>(); player.CheckAuthority(GetComponent <NetworkIdentity>(), player.GetComponent <NetworkIdentity>()); CmdChangeTransform(UnityARMatrixOps.GetPosition(hitTestResults[hitTestResults.Count - 1].worldTransform), UnityARMatrixOps.GetRotation(hitTestResults[hitTestResults.Count - 1].worldTransform)); CmdSetModelActive(); CmdSetConfirmButtonActive(); /* == UNET */ //Button.SetActive(true); } } } else if (adjustable) { if (Input.touchCount == 2) { var touch1 = Input.GetTouch(0); var touch2 = Input.GetTouch(1); if (touch1.phase == TouchPhase.Moved && touch2.phase == TouchPhase.Moved) { Vector3 screenPos = Camera.main.ScreenToViewportPoint((touch1.position + touch2.position) / 2); ARPoint point = new ARPoint { x = screenPos.x, y = screenPos.y }; List <ARHitTestResult> hitTestResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, ARHitTestResultType.ARHitTestResultTypeExistingPlane); //Model.transform.position = UnityARMatrixOps.GetPosition(hitTestResults[hitTestResults.Count - 1].worldTransform); /* UNET */ var player = ClientScene.localPlayers[0].gameObject.GetComponent <Player>(); player.CheckAuthority(GetComponent <NetworkIdentity>(), player.GetComponent <NetworkIdentity>()); CmdChangeTransform(UnityARMatrixOps.GetPosition(hitTestResults[hitTestResults.Count - 1].worldTransform), Model.transform.rotation); /* == UNET */ } //保证重新开始双指触摸记录的初始位置不是松开手时的位置,而是初始触摸的位置 if (Input.GetTouch(0).phase == TouchPhase.Began || Input.GetTouch(1).phase == TouchPhase.Began) { //记录初始位置 oldPosition1 = Input.GetTouch(0).position; oldPosition2 = Input.GetTouch(1).position; } if (Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(1).phase == TouchPhase.Moved) { //计算出当前两点触摸点的位置 var tempPosition1 = Input.GetTouch(0).position; var tempPosition2 = Input.GetTouch(1).position; float currentTouchDistance = Vector2.Distance(tempPosition1, tempPosition2); float lastTouchDistance = Vector2.Distance(oldPosition1, oldPosition2); //计算上次和这次双指触摸之间的距离差距 //然后去更改摄像机的距离 float distance = currentTouchDistance - lastTouchDistance; float scaleFactor = distance / 200f; Vector3 localScale = Model.transform.localScale; Vector3 scale = new Vector3(localScale.x + scaleFactor, localScale.y + scaleFactor, localScale.z + scaleFactor); //在什么情况下进行缩放 if (scale.x >= 0.2f && scale.y >= 0.2f && scale.z >= 0.2f) { //Model.transform.localScale = scale; var player = ClientScene.localPlayers[0].gameObject.GetComponent <Player>(); player.CheckAuthority(GetComponent <NetworkIdentity>(), player.GetComponent <NetworkIdentity>()); CmdChangeScale(scale); } //备份上一次触摸点的位置,用于对比 //也是松开手时的位置 oldPosition1 = tempPosition1; oldPosition2 = tempPosition2; } //if (Vector2.Dot(touch1.deltaPosition,touch2.deltaPosition)<=0 && touch1.position.y < touch2.position.y) //{ // Model.transform.Rotate(Vector3.down * touch1.deltaPosition.x * 0.75f, Space.World); //} //else if (Vector2.Dot(touch1.deltaPosition, touch2.deltaPosition) <= 0 && touch1.position.y > touch2.position.y) //{ // Model.transform.Rotate(Vector3.down * touch2.deltaPosition.x * 0.75f, Space.World); //} } else if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Moved) { Vector2 deltaPos = Input.GetTouch(0).deltaPosition; //Model.transform.Rotate(Vector3.down * deltaPos.x * 0.5f, Space.World); var player = ClientScene.localPlayers[0].gameObject.GetComponent <Player>(); player.CheckAuthority(GetComponent <NetworkIdentity>(), player.GetComponent <NetworkIdentity>()); CmdRotate(deltaPos); } } if (hintFinished) { time += Time.deltaTime; if (time > thresholdTime) { HintController.HideElement(); hintFinished = false;// not really unfinished } } }
// Update is called once per frame void Update() { remainingFlowers = gardenController.GetComponent <gardenController>().gardenFlowers - currentFlower; //int tempo = gardenController.GetComponent<gardenController>().gardenFlowers; int tempo = 100; beesCreated.text = gardenController.GetComponent <gardenController>().gardenBees - beeStack.Count + " bees fed"; beesRemaining.text = beeStack.Count + " bees left"; if (Input.touchCount > 0) { var touch = Input.GetTouch(0); if (touch.phase == TouchPhase.Began) { var screenPosition = Camera.main.ScreenToViewportPoint(touch.position); ARPoint point = new ARPoint { x = screenPosition.x, y = screenPosition.y }; List <ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent); if (hitResults.Count > 0) { foreach (var hitResult in hitResults) { Vector3 position = UnityARMatrixOps.GetPosition(hitResult.worldTransform); //add createheight to the y below placeLevel = new Vector3(position.x, position.y, position.z); bool UIZ = IsPointerOverUIObject(); if (currentFlower < 1000 && !UIZ) { if (tapCount == 0) { } alert.SetActive(false); CreateBall(placeLevel, twoFlower); currentFlower++; Debug.Log("current flower: " + currentFlower + ", total bees: " + beeStack.Count + ", position:" + placeLevel.x + ", " + placeLevel.y + ", " + placeLevel.z); tapCount++; // + ", remaining flowers: "+remainingFlowers } else if (totalBees == currentFlowerType && popUp.IsActive() == false) { // Debug.Log("SCENE RESET"); popUp2.gameObject.SetActive(true); } else if (keeper.Instance.currentGardenLevel == 4) { // SceneManager.LoadScene("Beez"); } else { Debug.Log("TRY AGAIN"); } break; } } } } }
private void UpdateImageAnchor(ARImageAnchor arImageAnchor) { //Debug.LogFormat("Anchor updated[{0}] : tracked {1}, name '{2}' GOs {3}", // arImageAnchor.Identifier, arImageAnchor.IsTracked, arImageAnchor.ReferenceImageName, _gameObjects.Count); int index; if (arImageAnchor.ReferenceImageName != null && int.TryParse(arImageAnchor.ReferenceImageName, out index) && index >= 0) { GameObject gameObjectToAHandle = null; if (index < _gameObjects.Count) { gameObjectToAHandle = _gameObjects[index]; } //Debug.LogFormat("Index {0} game object {1}", index, gameObjectToAHandle != null); if (gameObjectToAHandle != null) { if (arImageAnchor.IsTracked) { gameObjectToAHandle.transform.localPosition = UnityARMatrixOps.GetPosition(arImageAnchor.Transform); gameObjectToAHandle.transform.localRotation = UnityARMatrixOps.GetRotation(arImageAnchor.Transform); if (!gameObjectToAHandle.activeSelf) { gameObjectToAHandle.SetActive(true); } } else if (gameObjectToAHandle.activeSelf) { //gameObjectToAHandle.SetActive(false); } } else if (_hasTriggerObjects) { //Debug.LogFormat("Anchor re-added[{0}] : tracked {1}, name '{2}'", arImageAnchor.Identifier, arImageAnchor.IsTracked, arImageAnchor.ReferenceImageName); if (arImageAnchor.ReferenceImageName != null && int.TryParse(arImageAnchor.ReferenceImageName, out index) && index >= 0) { TriggerObject triggerObject; var triggerObjects = TriggerObjects; if (triggerObjects != null && triggerObjects.TryGetValue(index, out triggerObject)) { //Debug.LogFormat("Index {0} trigger object {1}", index, triggerObject != null); while (index >= _gameObjects.Count) { _gameObjects.Add(null); } var arObjectState = ArBehaviour.ArObjectState; if (arObjectState != null && _gameObjects[index] == null) { lock (arObjectState) { GameObject newGameObject; var result = ArBehaviour.CreateArObject( arObjectState, triggerObject.gameObject, null, transform, triggerObject.poi, triggerObject.poi.id, out newGameObject ); if (!ArBehaviourPosition.IsEmpty(result)) { ArBehaviour.ErrorMessage = result; return; } _gameObjects[index] = newGameObject; newGameObject.SetActive(true); } } } } } } }
private Vector3 GetWorldPosition(ARPlaneAnchor arPlaneAnchor) { return(UnityARMatrixOps.GetPosition(arPlaneAnchor.transform) + new Vector3(arPlaneAnchor.center.x, arPlaneAnchor.center.y, -arPlaneAnchor.center.z)); }
public void ARFrameUpdated(UnityARCamera camera) { if (AddedAndReadyToScale) { return; } // cast a ray to see if you tapped on an existing items, if so make that the current item to move around if (Input.touchCount > 0 && touchedScreen && !mySelectorOpen && MovingFloatObject == null && !TappedCloudPoint) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, maxRayDistance)) { if (hit.collider.name != "plane" && hit.collider.name != "Plane") { Message.text = "Tap to move, pinch to scale and tap Ok."; AddedAndReadyToScale = true; MovingFloatObject = hit.transform.gameObject; StartEditing(); return; } } } // did we just finish adding a object, if so listen for a new tap // this is to miss the tap on the okay button, I might be able to loose this if (TappedCloudPoint && !MovingFloatObject) { TappedCloudPoint = false; return; } // didn't tap on anything // the touch code to create and move that object if (Input.touchCount > 0 && touchedScreen && !mySelectorOpen && MovingFloatObject == null && !TappedCloudPoint) { var touch = Input.GetTouch(0); //var touchFinger2 = Input.GetTouch(1); var screenPosition = Camera.main.ScreenToViewportPoint(touch.position); point = new ARPoint { x = screenPosition.x, y = screenPosition.y }; // prioritize reults types // ARHitTestResultType[] resultTypes = { //ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingGeometry, //ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent, // if you want to use infinite planes use this: //ARHitTestResultType.ARHitTestResultTypeExistingPlane, //ARHitTestResultType.ARHitTestResultTypeEstimatedHorizontalPlane, //ARHitTestResultType.ARHitTestResultTypeEstimatedVerticalPlane, //ARHitTestResultType.ARHitTestResultTypeFeaturePoint //}; //hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface ().HitTest(point, resultTypes); // first try to mount to a feature point hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, ARHitTestResultType.ARHitTestResultTypeFeaturePoint); // if no points use the plane that was found //if (hitResults.Count < 1) //{ //hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point,ARHitTestResultType.ARHitTestResultTypeExistingPlane); //} //Debug.Log(hitResults.Count); if (hitResults.Count > 0) { TappedCloudPoint = true; ScreenBlocker.SetActive(false); foreach (var hitResult in hitResults) { position = UnityARMatrixOps.GetPosition(hitResult.worldTransform); break; } if (MovingFloatObject == null) { // create the object, there isn't one AddFloatObject(position); Message.text = "Created Object, pinch to scale... Tap Ok."; AddedAndReadyToScale = true; StartEditing(); } ScreenBlocker.SetActive(false); } } Logger.text = updateMessage; }
void Update() { if (Input.touchCount > 0) { var touch = Input.GetTouch(0); if (touch.phase == TouchPhase.Began) { touchLapse = 0f; var screenPosition = Camera.main.ScreenToViewportPoint(touch.position); var point = new ARPoint { x = screenPosition.x, y = screenPosition.y }; var hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent); if (hitResults.Count > 0) { foreach (var hitResult in hitResults) { var position = UnityARMatrixOps.GetPosition(hitResult.worldTransform); CreateDomino(new Vector3(position.x, position.y + createHeight, position.z)); break; } } else { Debug.Log("No hit"); } } else if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary) { touchLapse += Time.deltaTime; if (touchLapse < 0.5f) { return; } var screenPosition = Camera.main.ScreenToViewportPoint(touch.position); var point = new ARPoint { x = screenPosition.x, y = screenPosition.y }; var hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent); if (hitResults.Count > 0) { foreach (var hitResult in hitResults) { var position = UnityARMatrixOps.GetPosition(hitResult.worldTransform); if (Vector3.Distance(prevDominoPosition, position) < dominoDistance) { continue; } CreateDomino(new Vector3(position.x, position.y + createHeight, position.z)); break; } } } } }
void Update() { if (Input.GetMouseButtonDown(0) && CheckPanel.CheckPanel()) { Ray mRay = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit mHit; //射线检验 LayerMask mask = 1 << LayerMask.NameToLayer("Sphere");//只在Sphere层检测 if (Physics.Raycast(mRay, out mHit, 20f, mask.value) || CheckUIClick.OnClickUI()) { ; } else { var touch = Input.GetTouch(0); if (touch.phase == TouchPhase.Began) { Vector3 screenPos = Camera.main.ScreenToViewportPoint(touch.position); ARPoint point = new ARPoint { x = screenPos.x, y = screenPos.y }; List <ARHitTestResult> hitTestResults = UnityARSessionNativeInterface.GetARSessionNativeInterface().HitTest(point, ARHitTestResultType.ARHitTestResultTypeExistingPlane); if (flag == false && hitTestResults.Count > 0) { UnityARCameraManager.CloseDetection(); flag = true; GeneratePlane.GetComponent <FocusSquare>().enabled = false; FocusSquare.SetActive(false); HintController.ShowElement(3); } else if (flag && hitTestResults.Count > 0) { HintController.ShowElement(4); hintFinished = true; } /* == 第一次点击的时候关闭平面检测 */ if (currentObj[0].activeSelf == false) { //currentObj[0].transform.position = UnityARMatrixOps.GetPosition(hitTestResults[hitTestResults.Count - 1].worldTransform) + Vector3.up * currentObj[0].transform.localScale.y*0.1f; //currentObj[0].transform.position = UnityARMatrixOps.GetPosition(hitTestResults[hitTestResults.Count - 1].worldTransform); //currentObj[0].transform.rotation = UnityARMatrixOps.GetRotation(hitTestResults[hitTestResults.Count - 1].worldTransform); var player = ClientScene.localPlayers[0].gameObject.GetComponent <Player>(); player.CheckAuthority(GetComponent <NetworkIdentity>(), player.GetComponent <NetworkIdentity>()); CmdChangeTransform(0, UnityARMatrixOps.GetPosition(hitTestResults[hitTestResults.Count - 1].worldTransform), UnityARMatrixOps.GetRotation(hitTestResults[hitTestResults.Count - 1].worldTransform)); //currentObj[0].GetComponent<Touch>().ActiveBall(); //if (currentObj[1].activeSelf == true) currentObj[0].transform.position = new Vector3(currentObj[0].transform.position.x, currentObj[1].transform.position.y, currentObj[0].transform.position.z); } else if (currentObj[1].activeSelf == false) { //currentObj[1].transform.position = UnityARMatrixOps.GetPosition(hitTestResults[hitTestResults.Count - 1].worldTransform) + Vector3.up * currentObj[1].transform.localScale.y*0.1f; //currentObj[1].transform.position = UnityARMatrixOps.GetPosition(hitTestResults[hitTestResults.Count - 1].worldTransform); //currentObj[1].transform.rotation = UnityARMatrixOps.GetRotation(hitTestResults[hitTestResults.Count - 1].worldTransform); var player = ClientScene.localPlayers[0].gameObject.GetComponent <Player>(); player.CheckAuthority(GetComponent <NetworkIdentity>(), player.GetComponent <NetworkIdentity>()); CmdChangeTransform(1, UnityARMatrixOps.GetPosition(hitTestResults[hitTestResults.Count - 1].worldTransform), UnityARMatrixOps.GetRotation(hitTestResults[hitTestResults.Count - 1].worldTransform)); //currentObj[1].GetComponent<Touch>().ActiveBall(); //if (currentObj[0].activeSelf == true) currentObj[1].transform.position = new Vector3(currentObj[1].transform.position.x, currentObj[0].transform.position.y, currentObj[1].transform.position.z); } else { if (NoneUIClickEvent != null) { NoneUIClickEvent(); } } } } } if (hintFinished) { time += Time.deltaTime; if (time > thresholdTime) { HintController.HideElement(); hintFinished = false;// not really unfinished } } }
private void PerformHitTest(Vector2 touchPos) { var planeType = DetectedPlaneType.HorizontalUpwardFacing; if (Application.platform == RuntimePlatform.IPhonePlayer) { #if ARCORE_IOS_SUPPORT var session = UnityARSessionNativeInterface.GetARSessionNativeInterface(); var viewportPoint = Controller.MainCamera.ScreenToViewportPoint(touchPos); ARPoint arPoint = new ARPoint { x = viewportPoint.x, y = viewportPoint.y }; _hitResultList = session.HitTest(arPoint, ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent); if (_hitResultList.Count > 0) { // Fetch the closest hit result. int minDistanceIndex = GetMinDistanceIndex(_hitResultList); string identifier = _hitResultList[minDistanceIndex].anchorIdentifier; if (_arPlaneAligmentMapping.ContainsKey(identifier)) { planeType = _arPlaneAligmentMapping[identifier] == ARPlaneAnchorAlignment.ARPlaneAnchorAlignmentVertical ? DetectedPlaneType.Vertical : DetectedPlaneType.HorizontalUpwardFacing; } else { Debug.LogWarningFormat("Didn't find anchor identifier: {0}", identifier); return; } Pose hitPose = new Pose(); hitPose.position = UnityARMatrixOps.GetPosition( _hitResultList[minDistanceIndex].worldTransform); if (planeType == DetectedPlaneType.Vertical) { hitPose.rotation = UnityARMatrixOps.GetRotation( _hitResultList[minDistanceIndex].worldTransform); } else { // Point the hitPose rotation roughly away from the raycast/camera // to match ARCore. hitPose.rotation.eulerAngles = new Vector3(0.0f, Controller.MainCamera.transform.eulerAngles.y, 0.0f); } _hitPose = hitPose; var anchorGO = new GameObject("ARUserAnchor"); _anchorComponent = anchorGO.AddComponent <UnityARUserAnchorComponent>(); anchorGO.transform.position = hitPose.position; anchorGO.transform.rotation = hitPose.rotation; } #endif } else { TrackableHit arcoreHitResult = new TrackableHit(); if (Frame.Raycast(touchPos.x, touchPos.y, TrackableHitFlags.PlaneWithinPolygon, out arcoreHitResult)) { DetectedPlane plane = arcoreHitResult.Trackable as DetectedPlane; if (plane == null) { Debug.LogWarning("Hit test result has invalid trackable type: " + arcoreHitResult.Trackable.GetType()); return; } planeType = plane.PlaneType; _hitPose = arcoreHitResult.Pose; _anchorComponent = arcoreHitResult.Trackable.CreateAnchor(arcoreHitResult.Pose); } } if (_anchorComponent != null) { Instantiate(CloudAnchorPrefab, _anchorComponent.transform); // Attach map quality indicator to this pawn. var indicatorGO = Instantiate(MapQualityIndicatorPrefab, _anchorComponent.transform); _qualityIndicator = indicatorGO.GetComponent <MapQualityIndicator>(); _qualityIndicator.DrawIndicator(planeType, Controller.MainCamera); InstructionText.text = " To save this location, walk around the object to " + "capture it from different angles"; DebugText.text = "Waiting for sufficient mapping quaility..."; // Hide plane generator so users can focus on the object they placed. Controller.PlaneGenerator.SetActive(false); } }
// Updates the position of the probe and image anchor. Called by event. Method can't be renamed because its called by an event. void UpdateImageAnchor(ARImageAnchor arImageAnchor) { imageAnchorPosition = UnityARMatrixOps.GetPosition(arImageAnchor.transform); mGLEAM.probe.transform.position = imageAnchorPosition + mGLEAM.probeOffset; reflectiveObject.transform.position = imageAnchorPosition + mGLEAM.probeOffset; }
protected override void Update() { if (IsNewLayer) { _sessionStarted = false; } base.Update(); var layerItemList = LayerItemList; if (MenuEnabled.HasValue && MenuEnabled.Value && layerItemList != null && layerItemList.Any()) { var fitToScanOverlay = FitToScanOverlay; if (fitToScanOverlay != null && fitToScanOverlay.activeSelf) { long nowTicks = DateTime.Now.Ticks; var second = nowTicks / 10000000L; if (!_fitToScanOverlayActivationSecond.HasValue) { _fitToScanOverlayActivationSecond = second; //Debug.LogFormat("FTS value {0}", _fitToScanOverlayActivationSecond.Value); } else { var value = _fitToScanOverlayActivationSecond.Value; if (value + 30 < second) { //Debug.LogFormat("FTS value {0}, second {1}", _fitToScanOverlayActivationSecond.Value, second); var triggerObjects = TriggerObjects; if (triggerObjects != null) { foreach (var t in triggerObjects.Values) { t.isActive = false; } } _fitToScanOverlayActivationSecond = null; MenuButtonClick = new MenuButtonClickActivity { ArBehaviour = this }; } else { SetInfoText($"Timeout in {value + 30 - second} seconds."); } } } else { _fitToScanOverlayActivationSecond = null; } } #if IS_SLAM_APP #else if (!_sessionStarted) { if (!HasTriggerImages) { StartArSession(); return; } var anchorManager = AnchorManager.GetComponent <ArKitAnchorManager>(); anchorManager.ArBehaviour = this; anchorManager.TriggerObjects = TriggerObjects; anchorManager.FitToScanOverlay = FitToScanOverlay; StartArSession(anchorManager.TriggerObjects); } #endif if (m_camera != null && _sessionStarted) { // JUST WORKS! Matrix4x4 matrix = m_session.GetCameraPose(); m_camera.transform.localPosition = UnityARMatrixOps.GetPosition(matrix); m_camera.transform.localRotation = UnityARMatrixOps.GetRotation(matrix); m_camera.projectionMatrix = m_session.GetCameraProjection(); } }
void FaceUpdate(ARFaceAnchor anchorDate) { gameObject.transform.localPosition = UnityARMatrixOps.GetPosition(anchorDate.transform); gameObject.transform.localRotation = UnityARMatrixOps.GetRotation(anchorDate.transform); test = anchorDate.blendShapes; }
void FaceAdded(ARFaceAnchor anchorData) { currentBlendShapes = anchorData.blendShapes; model.transform.localPosition = UnityARMatrixOps.GetPosition(anchorData.transform); model.transform.localPosition = new Vector3(model.transform.localPosition.x, model.transform.localPosition.y + offsetY, model.transform.localPosition.z); }
//void ShowPlane(){ // Centerpos.transform.position=lastPlane.center; // Apos.transform.position = lastPlane.center+new Vector3(lastPlane.xhalf, 0,lastPlane.zhalf); // Bpos.transform.position = lastPlane.center+ new Vector3(lastPlane.xhalf, 0, -lastPlane.zhalf); // Cpos.transform.position = lastPlane.center+ new Vector3(-lastPlane.xhalf, 0, lastPlane.zhalf); // Dpos.transform.position = lastPlane.center+ new Vector3(-lastPlane.xhalf, 0, -lastPlane.zhalf); // } public float FindPlaneHeight(ARPlaneAnchor anchorData) { float _y = UnityARMatrixOps.GetPosition(anchorData.transform).y; return(_y); }