jueves, 5 de mayo de 2022

Como hacer con unity una persecucion de enemigo que dispara y ver los efectos.;

 

¿Como e echo el videojuego “Mission a-4”?

De momento voy a explicar una secuencia del videojuego en la que un enemigo persigue al player ,al protagonista del videojuego, y le va disparando.

En el video veis lo que explicare ahora.

Pondré los scrips siempre en C#.

Primero el script que hace que persiga al player, lo tiene el enemigo...


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

public class mepersigeelmalote : MonoBehaviour {

        Transform player;

        UnityEngine.AI.NavMeshAgent nav;


        void Awake ()
        {


            player = GameObject.FindGameObjectWithTag ("cano").transform;


            nav = GetComponent <UnityEngine.AI.NavMeshAgent> ();
        }


        void Update ()
        {
            
            nav.SetDestination (player.position);

        }
    }

--------------------------------------------------------------------

----------------------------------------------------------------

 

El enemigo ademas de este script necesita un NavMesh Navegation



 

Este elemento y el script consiguen que el enemigo persiga al player.

El player a de tener un tag para que lo reconozca el script, en este caso le llamamos “cano”, pero puede ser otro cualquiera que imaginemos un tag es un nombre inventado…

También tiene un script el enemigo para usar una barra de vida y que al recibir los disparos del player la barra de vida del enemigo mengue asta cambiarlo por otro enemigo una copia del mismo con la animación de estar abatido o muerto...es este script..

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ARRASA : MonoBehaviour {

    public int damage;
    public int vidaEnemigo;
    public Slider BarraVidaEnemigo;





    //public Rigidbody cubo;/// pruebas

    public Rigidbody ENEMIGOSALTAEXPLOTADO;/// pruebas
    //public Rigidbody source;/// pruebas


    //public Rigidbody  targetGameObject;/// pruebas


    void Update () {

        BarraVidaEnemigo.value = vidaEnemigo;

    }


    void OnTriggerEnter(Collider other) {
    //    if (other.gameObject.CompareTag ("Player")){
            if (other.gameObject.CompareTag ("caca")){

            vidaEnemigo-=damage;

            if (vidaEnemigo <= 0) {

                Destroy (this.gameObject);/////destruye funciona

            //    Application.LoadLevel (0);




                //Rigidbody p = Instantiate(cubo, transform.position, transform.rotation);////pruebassss
                Rigidbody p = Instantiate(ENEMIGOSALTAEXPLOTADO, transform.position, transform.rotation);////pruebassss

        // Instantiate(source, targetGameObject.transform.position,
                    //targetGameObject.transform.rotation);




            //    Application.LoadLevel (1);///cambia la escena donde quiero funciona


            }


        }}

}



También un script, siempre en C# para el sonido que al recibir un disparo el enemigo emita un sonido, de dolor o choque lo que se tercie...

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

public class SONIDOPUPAALMALO : MonoBehaviour {


        public AudioSource tickSource;

        void Start () {

            tickSource = GetComponent<AudioSource> ();

        }

        void Update () {
        }


        void OnTriggerEnter(Collider other) {
            if (other.gameObject.CompareTag ("caca")){

                tickSource.Play ();

            }}

    }

--------------------------------------------------------------

----------------------------------------------------------

------------------------------------------------------------

Este también tiene un Tag, nombre “caca” es el nombre de la bala del player que choca con el enemigo y provoca el sonido cuando le da....


 

En esta captura de encima de pantalla 2 scripts muy buenos para que el enemigo dispare al acercarse a cierta distancia del Player y que aga un fogonazo su arma, los dos funcionan exactamente igual solo hay que manipular algunos valores para que dispare desde mas cerca o mas lejos, mas rápido o mas lento, tiro a tiro o a ráfaga….están en un cubo que es hijo del gameobject arma.

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

public class DISPARATIRITO : MonoBehaviour {

        public Transform player;

        //  public float range = 1f;
        //public float range = 4f;
        public float range = 0.04f;


        public float bulletImpulse = 0.1f;

        private bool onRange = false;

        public Rigidbody projectile;

        void Start()
        {
             float rand = Random.Range(1.0f, 2.0f);/////ORIGINAL
            //float rand = Random.Range(0.04f, 2.0f);/////tambien funciona///////////////////////////EL QUE VENGO USANDO
            //float rand = Random.Range(0.04f, 0.5f);/////tambien funciona
            //float rand = Random.Range(0.04f, 0.08f);/////tambien funciona





            InvokeRepeating("Shoot", 2, rand);//////ORIGINAL



        }

        void Shoot()
        {

            if (onRange)
            {

                Rigidbody bullet = (Rigidbody)Instantiate(projectile, transform.position + transform.forward, transform.rotation);
                bullet.AddForce(transform.forward * bulletImpulse, ForceMode.Impulse);

                Destroy(bullet.gameObject, 2);
            }


        }

        void Update()
        {

            onRange = Vector3.Distance(transform.position, player.position) < range;

            if (onRange)
                transform.LookAt(player);
        }


    }

 -----------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------------------------------

-----------------------------------------------------------------------------------------------------------------------

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

public class FOGONAZOENEMIGO : MonoBehaviour {

        public Transform player;

        //  public float range = 1f;
        //public float range = 4f;
        public float range = 0.04f;


        public float bulletImpulse = 0.1f;

        private bool onRange = false;

        public Rigidbody projectile;

        void Start()
        {
            float rand = Random.Range(1.0f, 2.0f);/////ORIGINAL
            //float rand = Random.Range(0.04f, 2.0f);/////tambien funciona///////////////////////////EL QUE VENGO USANDO
            //float rand = Random.Range(0.04f, 0.5f);/////tambien funciona
            //float rand = Random.Range(0.04f, 0.08f);/////tambien funciona





            InvokeRepeating("Shoot", 2, rand);//////ORIGINAL



        }

        void Shoot()
        {

            if (onRange)
            {

                Rigidbody bullet = (Rigidbody)Instantiate(projectile, transform.position + transform.forward, transform.rotation);
                bullet.AddForce(transform.forward * bulletImpulse, ForceMode.Impulse);

                Destroy(bullet.gameObject, 2);
            }


        }

        void Update()
        {

            onRange = Vector3.Distance(transform.position, player.position) < range;

            if (onRange)
                transform.LookAt(player);
        }


    }

 

 ----------------------------------------------------------------------

---------------------------------------------------------------------

---------------------------------------------------------------------------

 

Detalles particulares de estos scripts son los prefabricados que usamos el del proyectil tiene el Rigidbody con la gravedad activada. El del fogonazo la tiene en Is Kinematic para que no se mueva, y los dos prefabricados tienen a su vez un script de tiempo para que se borren de la memoria cara ciertos segundos o décimas de segundo y el juego no se ralentice.

using System;
using UnityEngine;

namespace UnityStandardAssets.Utility
{
    public class TimedObjectDestructor : MonoBehaviour
    {
        [SerializeField] private float m_TimeOut = 1.0f;
        [SerializeField] private bool m_DetachChildren = false;


        private void Awake()
        {
            Invoke("DestroyNow", m_TimeOut);
        }


        private void DestroyNow()
        {
            if (m_DetachChildren)
            {
                transform.DetachChildren();
            }
            DestroyObject(gameObject);
        }
    }
}

 

 CONTINUARA EN CONSTRUCCION........