using System;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
namespace AibisDream.Utility
{
public static class CommonUtil
{
private const float Epsilon = 1e-5f;
private static Camera _mainCam;
///
/// 判断为0
///
/// 浮点数
/// 是否为0
public static bool IsZero(float value)
{
// 如果value小于epsilon,则认为它等于0
return Mathf.Abs(value) < Epsilon;
}
///
/// 判断浮点数是否相等
///
/// value1
/// value2
/// 是否相等
public static bool IsEqual(float value1, float value2)
{
return Mathf.Abs(value1 - value2) < Epsilon;
}
///
/// 简单延时实现
///
/// 延时
/// 函数
public static async Task Delay(int delayTime, Action action)
{
await Task.Delay(delayTime);
action?.Invoke();
}
///
/// 受限数值
///
/// 目标数
/// 上限
/// 下限
/// 结果
public static float Limit(float target, float max, float min)
{
if (target <= min)
{
return min;
}
if (target >= max)
{
return max;
}
return target;
}
///
/// 获取鼠标在世界中的位置
///
/// 鼠标界面位置
/// 物体形状
/// 世界位置
public static Vector3 GetMouseWorldPos(Vector3 mousePoint, Transform transform)
{
if (!_mainCam) _mainCam = Camera.main;
mousePoint.z = _mainCam.WorldToScreenPoint(transform.position).z;
return _mainCam.ScreenToWorldPoint(mousePoint);
}
///
/// 属性复制
///
/// 属性源
/// 属性目标
public static void CopyProperties(object source, object target)
{
var sourceProperties = source.GetType().GetProperties();
var targetProperties = target.GetType().GetProperties();
foreach (var sourceProperty in sourceProperties)
{
var targetProperty = targetProperties.FirstOrDefault(p =>
p.Name == sourceProperty.Name && p.PropertyType == sourceProperty.PropertyType);
if (targetProperty != null && targetProperty.CanWrite)
{
targetProperty.SetValue(target, sourceProperty.GetValue(source));
}
}
}
#region 链式扩展
public static T As(this object selfObj) where T : class
{
return selfObj as T;
}
public static T Self(this T self, Action onDo)
{
onDo?.Invoke(self);
return self;
}
public static T Self(this T self, Func onDo)
{
return onDo.Invoke(self);
}
#endregion
}
}