在半径范围内激活动画

时间:2020-07-10 23:38:57

标签: c# unity3d animation

我正在尝试为我的敌人炮塔创建脚本,但是效果不佳。我有一些被激活和停用的转塔动画。我需要的是根据与播放器的距离,播放两种动画。因此,一旦它在检测半径内移动,它就会播放激活动画,而一旦它在外面,它将播放去激活动画。我尝试的大多数其他方式都要求我创建一个动画控制器,我对此使用经验很少。我想要一种简单的方法来播放一个动画,当它在内部时播放,而当它在外面时,播放另一个动画。我认为有一种方法可以将动画剪辑存储在脚本中,然后进行播放。我已经附加了当前脚本,所以您知道我的意思了。

Check for unlimited crypto policies
Java version: 11.0.6+8-b520.43
restricted cryptography: true Notice: 'false' means unlimited policies
Security properties: limited
Max AES key length = 128

}

1 个答案:

答案 0 :(得分:0)

为每个update()计算并检查播放器的距离并不理想。它可以工作,但是它会做的工作量超出了玩家离它不远的地方。效率不高。

如果您的播放器是一个刚体,您想要做的是将一个SphereCollider添加到炮塔,设置isTrigger = true,将半径设置为您的检测半径,并处理OnTriggerEnter()和OnTriggerExit()事件以播放或停止动画。

您还可以在脚本中添加两个公共Animation对象,在编辑器中拖放动画,然后可以使用animation.Play()和.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.isPlaying并执行自己的animation.Stop()等。