繁体   English   中英

Unity3D - 在同一个脚本中巡逻多个路径的多个敌人

[英]Unity3D - Multiple enemies patrolling multiple paths in the same script

我是新编写的代码。 敌人将在两条路径之间巡逻。 然后,当玩家进入敌人周围的探测区域时,它将跟随玩家。

如果我想要多于1个敌人和多个路径,我将如何添加到此代码中以便能够执行此操作。 为每个敌人创建一个脚本将是一种浪费,对吗?

public var enemyPath1 : Transform;
public var enemyPath2 : Transform;
private var target : Transform = null;
private var characterControls: CharacterController;

function Start ()
{
    SetTarget(enemyPath1);
    characterControls = GetComponent(CharacterController);
}

function SetTarget(newTarget : Transform) : void
{
    target = newTarget;
}

function Update() : void
{
    var lookAtPosition : Vector3 = Vector3(target.position.x,
                                           this.transform.position.y,
                                           target.position.z);
    transform.LookAt(lookAtPosition);
    characterControls.SimpleMove(transform.forward);
}

function OnTriggerEnter(node : Collider) : void
{
    if(node.transform == target)
    {
        if(target == enemyPath1)
        {
            SetTarget(enemyPath2);
        }
        else if(target == enemyPath2)
        {
            SetTarget(enemyPath1);
        }
    }
}

这段代码应该进入敌人的游戏对象,对吧? 一种方法是将所有所需的路径放入一个数组中,按照它们应该被敌人跟随的顺序。

    var paths : Transform[];
    var pathIndex : int = 0;
    // Then in your start function:
    function Start ()
    {
        SetTarget(paths[pathIndex]);
        characterControls = GetComponent(CharacterController);
    }
    // Then in the function that is doing the checking and looking for the next path
    function OnTriggerEnter(node : Collider) : void
    {
        if(node.transform == target)
        {
            // Increment the index so it looks for the next path object
            pathIndex += 1;
            if(pathIndex == paths.length)
            {
                // Resets to the first path if this is the last one
                pathIndex = 0;
            }
            SetTarget(paths[pathIndex]);
        }
    }

因此,您可以将此脚本添加到场景中的所有敌方游戏对象,然后在编辑器中,您可以手动将其路径变量设置为您希望按所需顺序排列的任何路径,并且它们应遵循其设置例程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM