using UnityEngine;
using System.Collections;
public class ScanTest : MonoBehaviour {
//识别组件ImageTarget
public GameObject imageTargetObj;
private Vector3 imageTargetPos;
private float imageTargetHalfW;
private float imageTargetHalfH;
//识别图像在世界坐标
private Vector3 topLeftPosWorld;
private Vector3 bottomLeftPosWorld;
private Vector3 topRightPosWorld;
private Vector3 bottomRightPosWorld;
//图像在屏幕的四角坐标
private Vector2 topLeftPosScreen;
private Vector2 bottomLeftPosScreen;
private Vector2 topRightPosScreen;
private Vector2 bottomRightPosScreen;
//识别框的四角坐标
private Vector2 topLeftPosScan;
private Vector2 bottomLeftPosScan;
private Vector2 topRightPosScan;
private Vector2 bottomRightPosScan;
//画布的缩放比例计算
private float screenScale;
// Use this for initialization
void Start() {
imageTargetPos = imageTargetObj.transform.position;
//这里的10 的识别组件ImageTarget的size
imageTargetHalfW = 10 * 0.5f;
imageTargetHalfH = 10 * 0.5f;
topLeftPosWorld = imageTargetPos + new Vector3(-imageTargetHalfW, 0, imageTargetHalfH);
bottomLeftPosWorld = imageTargetPos + new Vector3(-imageTargetHalfW, 0, -imageTargetHalfH);
topRightPosWorld = imageTargetPos + new Vector3(imageTargetHalfW, 0, imageTargetHalfH);
bottomRightPosWorld = imageTargetPos + new Vector3(imageTargetHalfW, 0, -imageTargetHalfH);
//画布缩放适应是1080*1920 用宽度适应
screenScale = Screen.width / 1080f;
//计算一个1000*1000的识别框每个定点在位置
topLeftPosScan = new Vector2(Screen.width - 1000 * screenScale, Screen.height + 1000 * screenScale) * 0.5f;
bottomLeftPosScan = new Vector2(Screen.width - 1000 * screenScale, Screen.height - 1000 * screenScale) * 0.5f;
topRightPosScan = new Vector2(Screen.width + 1000 * screenScale, Screen.height + 1000 * screenScale) * 0.5f;
bottomRightPosScan = new Vector2(Screen.width + 1000 * screenScale, Screen.height - 1000 * screenScale) * 0.5f;
}
// Update is called once per frame
void Update() {
//将识别图的位置映射到屏幕坐标
topLeftPosScreen = Camera.main.WorldToScreenPoint(topLeftPosWorld);
bottomLeftPosScreen = Camera.main.WorldToScreenPoint(bottomLeftPosWorld);
topRightPosScreen = Camera.main.WorldToScreenPoint(topRightPosWorld);
bottomRightPosScreen = Camera.main.WorldToScreenPoint(bottomRightPosWorld);
//比较识别图四个角的坐标和识别框4个角的坐标 如果都在里面了就在框中间了
if (topLeftPosScreen.x > topLeftPosScan.x && topLeftPosScreen.y < topLeftPosScan.y) {
if (bottomLeftPosScreen.x > bottomLeftPosScan.x && bottomLeftPosScreen.y > bottomLeftPosScan.y) {
if (topRightPosScreen.x < topRightPosScan.x && topRightPosScreen.y < topRightPosScan.y) {
if (bottomRightPosScreen.x < bottomRightPosScan.x && bottomRightPosScreen.y > bottomRightPosScan.y) {
//识别图在框中了!
}
}
}
}
}
}
注意:识别框的坐标就是 1000*1000
识别图的坐标是运行后扫描出识别图后的这个图的4点坐标(变的),