统一2D:简单的敌人射击

时间:2017-07-19 05:23:33

标签: c# unity3d

我正在开发2D游戏。如果我想要一个简单的敌人经典每5秒左右射击一次,我该怎么办呢?

我知道我需要添加一个colider和rigidbody但不太确定如何处理这个问题,因为我仍然掌握了整个想法

Red = Enemy/ Rough idea/Sketch

谢谢

2 个答案:

答案 0 :(得分:1)

你想要的是创造一种类型的游戏对象用作子弹'。这个游戏对象在产生时会有一个脚本让它沿某个方向行进。

您可以使用力(物理)移动它们,或者您可以将它们从一个地方转换为另一个地方,这样就可以将它们移动到绝对的地方。并忽略环境中的物理。

然后你可以在这个对象上使用对撞机来检测它何时使用OnCollisionEnter方法或OnTriggerEnter方法击中玩家。

这里有一些教程,所以我希望他们有所帮助。 Creating Shooting

答案 1 :(得分:0)

首先,您需要考虑敌人的举止,只要并肩行走或将其命名为Navmesh。

我在统一网站上找到了这个脚本:

使用UnityEngine; 使用System.Collections;

公共类EnemyAttack:MonoBehaviour {     public float timeBetweenAttacks = 0.5f; //两次攻击之间的时间(以秒为单位)。     public int AttackDamage = 10; //每次攻击夺走的生命值。

Animator anim;                              // Reference to the animator component.
GameObject player;                          // Reference to the player GameObject.
PlayerHealth playerHealth;                  // Reference to the player's health.
EnemyHealth enemyHealth;                    // Reference to this enemy's health.
bool playerInRange;                         // Whether player is within the trigger collider and can be attacked.
float timer;                                // Timer for counting up to the next attack.


void Awake ()
{

    player = GameObject.FindGameObjectWithTag ("Player");
    playerHealth = player.GetComponent <PlayerHealth> ();
    enemyHealth = GetComponent<EnemyHealth>();
    anim = GetComponent <Animator> ();
}

// OntriggerEnter和On TriggerExit每次玩家进入时发生碰撞,敌人都会跟随敌人,并在玩家退出时停止     void OnTriggerEnter(对撞机其他)     {         //如果进入的对撞机是玩家...         if(other.gameObject ==玩家)         {             // ...玩家在范围内。             playerInRange = true;         }     }

void OnTriggerExit (Collider other)
{
    // If the exiting collider is the player...
    if(other.gameObject == player)
    {
        // ... the player is no longer in range.
        playerInRange = false;
    }
}


void Update ()
{
    // Add the time since Update was last called to the timer.
    timer += Time.deltaTime;

    // If the timer exceeds the time between attacks, the player is in range and this enemy is alive...
    if(timer >= timeBetweenAttacks && playerInRange && enemyHealth.currentHealth > 0)
    {
        // ... attack.
        Attack ();
    }

    // If the player has zero or less health...
    if(playerHealth.currentHealth <= 0)
    {
        // ... tell the animator the player is dead.
        anim.SetTrigger ("PlayerDead");
    }
}


void Attack ()
{
    // Reset the timer.
    timer = 0f;

    // If the player has health to lose...
    if(playerHealth.currentHealth > 0)
    {
        // ... damage the player.
        playerHealth.TakeDamage (attackDamage);
    }
}

}