void oncollisionenter 发生了多少次?

how many times void oncollisionenter happens?

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;
    }
}