Galería de tiro. Disparo Unity 3D Raycast

Materiales didácticos para la escuela de programación. Parte 17

Los tutoriales anteriores se pueden encontrar aquí:
  1. Astronave





  2. Dominó





  3. Pájaro flappy





  4. Sala de gravedad





  5. Platformer





  6. Árboles (complemento SpeedTree)





  7. Modelando una casa en SketchUp





  8. Casa en el bosque





  9. Efecto lluvia. Partículas





  10. Billar





  11. Carácter líquido





  12. Cumplir y trabajar con el sistema de eventos





  13. Sintetizador Unity 3D





  14. Aerodeslizador





  15. Ragdolls en Unity 3D





  16. Cómo funcionan los vectores. Unidad de baloncesto 3D





En este proyecto, consideraremos el proceso de trabajo:





  • con raycasts y vectores;





  • con métodos de otras clases personalizadas;





  • con AudioSource y con Rigidbody a través del código;





  • tres componentes principales de un disparo que afectan psicológicamente al jugador (sonido, luz y brillo, animación y el rastro del disparo);





  • instanciación de casas prefabricadas.





Los temas clave del proyecto son precisamente los raycasts y los vectores. Esto último, es necesario dedicar bastante tiempo todos los días, y explicar cómo funcionan con ejemplos sencillos. Pero si logró completar rápidamente un proyecto con los estudiantes, entonces en esta lección será apropiado considerar el sistema mecanim.





Orden de ejecución

Crea un nuevo proyecto, importa el activo adjunto .





Además de los recursos estándar, el paquete tiene un complemento de terceros para pintar calcomanías. Su trabajo no está cubierto en el contexto de esta lección.





El proyecto de la lección se divide en 2 partes: campo de tiro y granadas.





Galería de tiro

- . , , , , .





, , .





DecalShooter, , , . .

, . , Y , CapsuleCollider MeshCollider Convex. , , point light, , AudioSource , Rigidbody Continius Dynamic isKinematik. AudioSource PlayOnAwake .





Target, .





, . .





using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Target : MonoBehaviour {
    public GameObject light;
    public Rigidbody rig;
    public AudioSource src;
 
    bool enabled = true;
 
    // Use this for initialization 
    void Start() {
        rig = GetComponent<Rigidbody>();
        src = GetComponent<AudioSource>(); 
    }
 
    // Update is called once per frame 
    void Update() {
 
    }
 
    public void shoot() {
        if (!enabled) {
           return;
        }
 
        rig.isKinematic = false; 
        light.SetActive(false); 
        src.Play();
 
        enabled = false;
    }
 
}

      
      



 ​shoot,​ , . - DecalShooter  ​shoot. :





   if (Input.GetKeyDown(KeyCode.Mouse0)) {
            time = 0.3f; 
            ShootSource.Play(); 
            anim.Play("fire"); 
            Muzzleflash.SetActive(true);
            //   
            RaycastHit hitInfo;
            Vector3 fwd = transform.TransformDirection(Vector3.forward); 
            
            if (Physics.Raycast(transform.position, fwd, out hitInfo, 100f)) {
                GameObject go = Instantiate(
                    DecalPrefab,
                    hitInfo.point, 
                    Quaternion.LookRotation(
                        Vector3.Slerp(-hitInfo.normal, fwd, normalization) 
                    )
                ) as GameObject;
                go.GetComponent<DecalUpdater>().UpdateDecalTo(
                    hitInfo.collider.gameObject, 
                    true
                );
                Vector3 explosionPos = hitInfo.point;
                Target trg = hitInfo.collider.GetComponent<Target>();
                
                if (trg) {
                    trg.shoot();
                }
                
                Rigidbody rb = hitInfo.collider.GetComponent<Rigidbody>();
                
                if (rb != null) {
                    rb.AddForceAtPosition(fwd * power, hitInfo.point, ForceMode.Impulse);
                    Debug.Log("rb!");
                } 
            }
            //   
        }
      
      



hitInfo , ,  ​shoot.​ , , . , . , , . Target :





light.SetActive(false);
      
      







light.GetComponent<Light>().color = Color.red;
      
      



, .





.





, - .





using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
public class Lenght :  MonoBehaviour {
    public Text Dalnost;
    float rasstoyanie = 0; //     
 
    // Use this for initialization 
    void Start() {
 
    }
 
    // Update is called once per frame 
    void Update() {
        RaycastHit hitInfo;
        
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hitInfo, 200)) {
            rasstoyanie = hitInfo.distance;
            Dalnost.text = rasstoyanie.ToString();
        }
    }
}
      
      



FPScontroller/FirstPersonCharacter. Canvas , .

, , .

.





- . , . , .





using System.Collections;
using System.Collections.Generic; 
using UnityEngine;
using UnityEngine.UI;
 
public class Length :  MonoBehaviour {
    public Text Dalnost;
    float rasstoyanie = 0; //      
    public GameObject sharik;
 
    // Use this for initialization
    void Start() {
 
    }
 
    // Update is called once per frame 
    void Update() {
        RaycastHit hitInfo; 
        
        if(Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), outhitInfo, 200)) {
            rasstoyanie = hitInfo.distance; 
            Dalnost.text = rasstoyanie.ToString ();
            if(Input.GetKeyDown(KeyCode.Mouse1)) {
                GameObject go = Instantiate(
                    sharik, 
                    transform.position + Vector3.Normalize(hitInfo.point - transform.position), 
                    transform.rotation
                );
                Rigidbody rig = go.GetComponent<Rigidbody>();
                rig.velocity = Vector3.Normalize(hitInfo.point - transform.position) * 10;
            } 
        }
    } 
}
      
      



- ? , . . .. , , . . Grenade.





using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Grenade :  MonoBehaviour {
    public Transform explosionPrefab;
 
    void OnCollisionEnter(Collision collision) {
        ContactPoint contact = collision.contacts[0];
        
        // Rotate the object so that the y-axis faces along the normal of the surface
        Quaternion rot = Quaternion.FromToRotation(Vector3.up, contact.normal);
        Vector3 pos = contact.point; 
        Instantiate(explosionPrefab, pos, rot);
        Destroy(gameObject);
    }
}
      
      



, Body Convex, RIgidbody . .





, , , .





. , AudioSource PlayOnAwake , Spital Blend 90 3 .





Para resolver todos los efectos y la distribución de Rigidbody correctamente, necesita crear otro script. Lo llamaremos Explosión:





using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Explosion :  MonoBehaviour {
    public float radius = 5.0f;
    public float power = 10.0f;
    public GameObject svet;

    void Start() {
        Destroy(svet, 0.1f);

        Vector3 explosionPos = transform.position;
        Collider[] colliders = Physics.OverlapSphere(explosionPos, radius);

        foreach(Collider hit in colliders) {
            Rigidbodyrb = hit.GetComponent<Rigidbody>();
            if (rb != null) {
                rb.AddExplosionForce(power, explosionPos, radius, 3.0f);
            }
        }
    }
}
      
      



Debe lanzarlo sobre el efecto de explosión y crear una casa prefabricada.





Esta casa prefabricada se utiliza en el guión de granada para crear una explosión.





¡Hecho!








All Articles