Unity 小功能
1.物体a看向物体b方向,而忽略b的高度
private void LookTargetDirection(Transform target)
{
var dic = (target.position - transform.position).normalized;
dic.y = 0;
if (dic != Vector3.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(dic);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 20f); //看向目标
}
}
2.延迟调用方法
public void WaitActionTime(float timer, Action act)
{
StartCoroutine(DelayAction(timer, act));
}
public IEnumerator DelayAction(float timer, Action callback)
{
yield return new WaitForSeconds(timer);
callback?.Invoke();
}
3.代码指定动画添加事件
public void GetAnim(string aniName)
{
// 获取动画控制器中的所有动画剪辑
RuntimeAnimatorController runtimeController = ani.runtimeAnimatorController;
if (runtimeController == null)
{
Debug.LogError("Animator Controller 未找到!");
return;
}
AnimationClip[] animationClips = runtimeController.animationClips;
if (animationClips == null || animationClips.Length == 0)
{
Debug.LogError("未找到动画剪辑!");
return;
}
// 遍历动画剪辑
foreach (AnimationClip clip in animationClips)
{
Debug.Log("找到动画剪辑: " + clip.name);
// 如果找到目标动画剪辑
if (clip.name == aniName)
{
// 添加动画事件
AddEventToClip(clip);
Debug.Log("已为动画剪辑 " + clip.name + " 添加动画事件");
}
}
}
// 添加动画事件
void AddEventToClip(AnimationClip clip)
{
// 创建动画事件
AnimationEvent animationEvent = new AnimationEvent
{
time = 0.7f, // 事件触发时间(秒)
functionName = "OnAnimationEvent", // 回调函数名称
stringParameter = "Hello from Animation Event!" // 传递的参数
};
// 将事件添加到动画剪辑
clip.AddEvent(animationEvent);
}
// 动画事件回调函数
void OnAnimationEvent(string message)
{
Debug.Log("动画事件触发: " + message);
StoneMove();
}
4.距离范围检测
bool IsTargetInRange(float range)
{
float distance = Vector3.Distance(transform.position, target.position);
return distance <= range;
}
5.编辑器选中物体并绘制范围线条
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red; // 设置 Gizmos 的颜色
Gizmos.DrawWireSphere(transform.position, range); // 绘制一个半径为 range 米的线框球体
}
6.范围内施加爆炸力
void Explode()
{
// 检测以物体为中心,半径为 explosionRadius 的周围所有碰撞体
Collider[] colliders = Physics.OverlapSphere(transform.position, explosionRadius);
foreach (Collider collider in colliders)
{
Rigidbody rb = collider.GetComponent<Rigidbody>(); // 获取碰撞体的 Rigidbody 组件
// 对周围物体施加爆炸力
rb.constraints = RigidbodyConstraints.None;
rb.useGravity = true;
rb.AddExplosionForce(100, transform.position, 10, 1, ForceMode.Impulse);
}
}