在半径范围内激活动画



我正试图为我的敌人炮塔创建一个脚本,但进展不顺利。我有几个炮塔被激活和停用的动画。我需要的是,根据与玩家的距离,它可以播放任意一个动画。因此,一旦它在检测半径内移动,就会播放激活动画,一旦它位于检测半径外,就会播放去激活动画。我尝试的大多数其他方法都需要创建一个动画控制器,而我在使用它方面几乎没有经验。我想要一种简单的方法,当一个动画在里面时播放,当它在外面时播放不同的动画。我认为有一种方法可以将动画片段存储在脚本中,然后播放。我已经附上了我当前的脚本,所以你知道我的意思。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyTurret : MonoBehaviour
{
public GameObject Player;
public float DistanceToPlayer;
public float DetectionRadius = 75;
// Start is called before the first frame update
void Start()
{
Player = GameObject.FindGameObjectWithTag("PlayerTank");
}
// Update is called once per frame
void Update()
{
DistanceToPlayer = Vector3.Distance(transform.position, Player.transform.position);
if (DistanceToPlayer<=DetectionRadius)
{
Debug.Log("Within Radius");
}
if (DistanceToPlayer >= DetectionRadius)
{
Debug.Log("Outside Radius");
}
}

}

为每次更新((计算和检查玩家的距离并不理想。它会起作用,但当玩家甚至不在它附近时,它会做比需要做的更多的工作。它没有效率。

如果你的玩家是刚体,你可能想做的是在炮塔中添加一个SphereCollider,设置isTrigger=true,将半径设置为你的检测半径,并处理OnTriggerEnter((和OnTriggerExit((事件来播放或停止动画。

还可以将两个公共动画对象添加到脚本中,在编辑器中拖放动画,然后可以使用动画。播放((和。Stop((等来控制动画。

类似的东西。没有经过充分的测试,但你可以理解。

public float detectionRadius = 75;
public Animation activateAnimation;
public Animation deactivateAnimation;
void Start()
{
SphereCollider detectionSphere = gameObject.AddComponent<SphereCollider>();
detectionSphere.isTrigger = true;
detectionSphere.radius = detectionRadius;
detectionSphere.center = Vector3.zero;
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "PlayerTank")
{
activateAnimation.Play();
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "PlayerTank")
{
deactivateAnimation.Play();
}
}

你的动画不能循环,否则你将不得不添加更多的逻辑来检查animation.isPlay和做你自己的动画。停止((等

最新更新