예제 #1
0
    // called when we want to shoot a bullet
    public void Shoot()
    {
        lastShootTime = Time.time;

        //audioSource.PlayOneShot(shootSfx);

        if (isPlayer)
        {
            // https://docs.unity3d.com/ScriptReference/RaycastHit-point.html
            var ray = cam.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hitInfo))
            {
                if (hitInfo.point.z < muzzle.position.z) // if the hit was closer to the camera than the muzzle
                {
                    return;                              // do not fire
                }
                SpawnableObject bullet = bulletSpawner.Get(bulletIndex);
                bullet.transform.position = muzzle.position;
                Vector3 dir = (hitInfo.point - muzzle.position).normalized;
                bullet.GetComponent <Rigidbody>().velocity = dir * bulletSpeed;
            }
            else // if the raycast misses any object
            {
                Vector3         aimed  = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 40));
                SpawnableObject bullet = bulletSpawner.Get(bulletIndex);
                bullet.transform.position = muzzle.position;
                Vector3 dir = (aimed - muzzle.position).normalized;
                bullet.GetComponent <Rigidbody>().velocity = dir * bulletSpeed;
            }
        }
        else // if an enemy
        {
            SpawnableObject bullet = bulletSpawner.Get(bulletIndex);
            bullet.transform.position = muzzle.position;
            Vector3 dir = (target.transform.position - muzzle.position).normalized;
            bullet.GetComponent <Rigidbody>().velocity = dir * bulletSpeed;
        }
    }