判断物体是否在相机视野中
/// <summary>
/// 判断物体是否在相机视野
/// </summary>
/// <param name="worldPos"></param>
/// <returns></returns>
public static bool IsInView(Vector3 worldPos, Camera ca = null)
{
if (ca == null) ca = Camera.main;
if (ca == null) return false;
Transform camTransform = ca.transform;
Vector2 viewPos = ca.WorldToViewportPoint(worldPos);
Vector3 dir = (worldPos - camTransform.position).normalized;
float dot = Vector3.Dot(camTransform.forward, dir); //判断物体是否在相机前面
if (dot > 0 && viewPos.x >= 0 && viewPos.x <= 1 && viewPos.y >= 0 && viewPos.y <= 1)
return true;
else
return false;
}
判断物体是否在相机内
/// <summary>
/// 判断物体是否在相机内
/// </summary>
/// <param name="worldPos"></param>
/// <returns></returns>
public static bool IsInCamera(Vector3 worldPos, Camera ca = null)
{
if (ca == null) ca = StageManager.I.GetSceneCamera();
if (ca == null) return false;
Vector3 localPosition = ca.transform.InverseTransformPoint(worldPos);
float z = localPosition.z;
if (z < ca.nearClipPlane || z > ca.farClipPlane) return false;
float scale = (z - ca.nearClipPlane) / (ca.farClipPlane - ca.nearClipPlane);
float tan = Mathf.Tan(ca.fieldOfView * 0.5f * Mathf.Deg2Rad);
float nearHeight = ca.nearClipPlane * tan * 1.2f;
float farHeight = ca.farClipPlane * tan * 1.2f;
float halfHeight = (farHeight - nearHeight) * scale;
float y = localPosition.y;
if (y < -halfHeight || y > halfHeight) return false;
float halfWidth = halfHeight * ca.aspect;
float x = localPosition.x;
if (x < -halfWidth || x > halfWidth) return false;
return true;
}
判断点是否在多边形内
以下是检查点是在内部还是外部的简单想法。
1)在每个点的右侧绘制一条水平线并将其延伸到无穷大
2)计算线与多边形边相交的次数。
3)如果交叉点的数量为奇数,则点在多边形内部。否则,那么点在外面。
/// <summary>
/// 射线法:判断点是否在多边形内
/// 射线穿过多边形边界的次数为奇数时点在多边形内
/// </summary>
/// <param name=''></param>
/// <returns></returns>
public static bool IsPointInPolygon(Vector3 point, Vector3[] polygon)
{
int polygonLength = polygon.Length, i = 0;
bool inside = false;
float pointX = point.x, pointZ = point.z;
float startX, startZ, endX, endZ;
Vector3 endPoint = polygon[polygonLength - 1];
endX = endPoint.x;
endZ = endPoint.z;
while (i < polygonLength)
{
startX = endX;
startZ = endZ;
endPoint = polygon[i++];
endX = endPoint.x;
endZ = endPoint.z;
inside ^= (endZ > pointZ ^ startZ > pointZ) && ((pointX - endX) < (pointZ - endZ) * (startX - endX) / (startZ - endZ));
}
return inside;
}
加载非resource文件纹理
public static IEnumerator LoadLocalImage(string url, Image image)
{
string filePath = "file:///" + url;
Debug.Log("getting local image:" + filePath);
WWW www = new WWW(filePath);
yield return www;
Texture2D texture = www.texture;
Sprite m_sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
image.sprite = m_sprite;
}