Unity 3d中是否可以检测碰撞发生了多少次?

例如,如果3次则杀死敌人。

或两次将寿命减少50%。

我想用void OnCollisionEnter函数来做到这一点。

这是我的AI代码和我的玩家代码:

public Transform[] Targets;
private int DestPoint = 0;
private NavMeshAgent Agent;
public Transform Player;
public Rigidbody Bullet;
public Transform Instantiator;
public float BulletSpeed;
public float fireRate;
private float nextFire = 0F;

void Start()
{
    Agent = GetComponent<NavMeshAgent> ();
    Agent.autoBraking = false;
}

void Update()
{
    if (Vector3.Distance(transform.position, Player.position) < 100)
    {
        transform.LookAt (Player);
        if (Time.time > nextFire)
        {
            nextFire = Time.time + fireRate;
            Agent.Stop ();
            Shoot ();
        }
    }
    else if (Vector3.Distance(transform.position, Player.position) > 100)
    {
        GotoNextPoint ();
    }
}

void GotoNextPoint()
{
    Agent.destination = Targets [DestPoint].position;
    DestPoint = (DestPoint + 1) % Targets.Length;
}

void Shoot()
{
    Rigidbody Clone = Instantiate (Bullet, Instantiator.position, Instantiator.rotation) as Rigidbody;
    Clone.AddForce (Instantiator.forward * Time.deltaTime * BulletSpeed);
}

public float Speed;
public float RotationSpeed;
public Rigidbody Bullet;
public float BulletSpeed;
public Transform Instantiator;
public float fireRate;
private float nextFire = 0F;

void Update()
{
    if (CrossPlatformInputManager.GetAxis("Vertical") > 0)
    {
        transform.Translate (Vector3.forward * Time.deltaTime * Speed);
    }
    if (CrossPlatformInputManager.GetAxis("Vertical") < 0)
    {
        transform.Translate (Vector3.back * Time.deltaTime * Speed);
    }
    if (CrossPlatformInputManager.GetAxis("Horizontal") > 0)
    {
        transform.Rotate (Vector3.up * Time.deltaTime * RotationSpeed);
    }
    if (CrossPlatformInputManager.GetAxis("Horizontal") < 0)
    {
        transform.Rotate (Vector3.down * Time.deltaTime * RotationSpeed);
    }

    if (CrossPlatformInputManager.GetButtonDown ("Shoot") && Time.time > nextFire)
    {
        nextFire = Time.time + fireRate;
        Rigidbody Clone = Instantiate (Bullet, Instantiator.position, Instantiator.rotation);
        Clone.AddForce (Instantiator.forward * Time.deltaTime * BulletSpeed);
    }
}

最佳答案

OnCollisionEnter函数没有为此内置的变量或函数。您必须为此创建一个变量,然后在每次冲突时增加该变量。没有其他方法可以做到这一点。

int collisonCounter = 0;

void OnCollisionEnter(Collision collision)
{
    //Increment Collison
    collisonCounter++;

    if (collisonCounter == 2)
    {
        //reduce the life by 50 percent

    }

    if (collisonCounter == 3)
    {
        // kill the enemy


        //Reset counter
        collisonCounter = 0;
    }
}

09-25 19:41