miércoles, 12 de enero de 2022

¿Como funciona un sistema de sumar puntos en Unity?;

¿Como funciona un sistema de sumar puntos en Unity?

En las capturas de pantalla se pueden ver los elementos que intervienen para dicha labor...como si fuera una receta de cocina lo voy a explicar….

Ingredientes….

1-Un script en c#.

2- Un Canvas con dos text.

3- Un collider con el trigger acribado en este caso una esfera que lo tiene el player el hombre lobo y que tendrá el contenido del script en C#.

4- Un Tag con un nombre inventado en este caso le llamamos ”MATA” y se lo aplicamos a los enemigos, al nombre del Tag me refiero y ellos a su vez un cubo por encima de su cabeza también con el trigger activado.

5- A continuación el script y video de referencia.

 


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

        // Create public variables for player speed, and for the Text UI game objects
        public float speed;
        public Text countText;
        public Text winText;

        // Create private references to the rigidbody component on the player, and the count of pick up objects picked up so far
        private Rigidbody rb;
        private int count;/// <summary>

        void Start ()
        {


            // Assign the Rigidbody component to our private rb variable
            rb = GetComponent<Rigidbody>();

            // Set the count to zero 
            count = 0;

            // Run the SetCountText function to update the UI (see below)
            SetCountText ();

            // Set the text property of our Win Text UI to an empty string, making the 'You Win' (game over message) blank
            winText.text = "";
        }

        // store a reference to that collider in a variable named 'other'..
        void OnTriggerEnter(Collider other) 
        {

            //if (other.gameObject.CompareTag ("ogri2"))
            if (other.gameObject.CompareTag ("MATA"))

            {
                // Make the other game object (the pick up) inactive, to make it disappear
                other.gameObject.SetActive (false);///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                // Add one to the score variable 'count'
                count = count + 1;


                // Run the 'SetCountText()' function (see below)
                SetCountText ();
            }
        }

        // Create a standalone function that can update the 'countText' UI and check if the required amount to win has been achieved
        void SetCountText()
        {
            // Update the text field of our 'countText' variable
            //countText.text = "Count: " + count.ToString ();

            countText.text = "PUNTOS: " + count.ToString ();
            // Check if our 'count' is equal to or exceeded 12
            if (count == 11) 
                //if (count >= 11) /////////original
                //if (count >= 111112) ////////7original
            {



            }
        }
    }


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

cambio de escena por colision y nombrado por tag el gameobject
------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class portoquedetaccambialaescena : MonoBehaviour {


        void Start () {

        }




        //void OnCollisionEnter (){


        void OnCollisionEnter (Collision collision)
        {
            //if (collision.gameObject.tag == "maloazul (4)") {
            //Destroy (gameObject, 0.0f); 


            if (collision.gameObject.tag == "pomada") {
                Destroy (gameObject, 2.0f); 

                //    transform.position = new Vector3 (198.301f, 20.316f, 136.023f);/////////nuebo mio
                //transform.Translate (new Vector3 (198 * Time.deltaTime, 20, 136.2f), Space.Self);/////////////IMBENTADO

                //Application.LoadLevel (1);////ORIGINALLLLLLLLLLLL
                Application.LoadLevel (1);




            }
        }
    }



martes, 11 de enero de 2022

IA inteligencia artificial persecución de los enemigos;

 

IA inteligencia artificial persecución de los enemigos


 

Voy avanzando mi blog con lo que estoy haciendo en la clonación de enemigos que me persiguen y destruyo de un zarpazo, el resultado es medio satisfactorio, falta pulir mucho, pero voy contando en el blog, en el video se ven imágenes de unos personajes medio trabajados que arian de vigilantes de seguridad y que irían persiguiendo al hombre lobo, este a su vez da unos zarpazos y les va arrancando la cabeza, también hay una mujer a la que se le acerca y de un zarpazo le arranca la cabeza.



1-el primer paso a sido poner un origen de las clonaciones de los personajes guardias de seguridad,

se van creando continuamente y les e puesto un Nav Mesh Agent.

2-E preparado el terreno, en este caso es un cubo que hace de suelo modelado con esa forma y desde el que puse la navegation...ver imagen


 

creí solo se podía hacer esto en un terreno típico de Unity pero yo lo echo partiendo de un cubo.

3- Un dato importante, los guardias no parten de base de las clonaciones, la base es un cubo que hace de padre sobre el que va el personaje de hijo el mismo guardia de seguridad en si mismo, e tenido que hacerlo así por que cuando iban apareciendo en cadena uno de tras del otro se auto destruían y aparecía el mismo personaje que no tiene cabeza y esta decapitado, porque los guardias tienen el script del actibate trigger que produce este cambio, e probado cambiar la velocidad de su Nav Mesh Agent. Para que no se tocasen entre si al ir clonándose pero no me funciono,




 



En la imagen se ven los personajes que están en prefabricado, la cabeza suelta, el cuerpo decapitado son los que aparecen con el script de ActivateTrigger, al colisionar el zarpazo en la parte de la cabeza del guardia, como se ve en el video de YouTube, desde luego aun falta muchísimo trabajo y muchísima practica del tema y aprendizaje...pero empiezo a construir unos personajes que me persiguen amenazadoramente, a esto e de añadirle un sistema de puntuación pero lo explicare mas adelante ademas de un sistema de vidas que valla perdiendo el hombre lobo si le atacan los guardias…..

.....................scripts ............................................


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

public class persecuciondeenmigoasiento2 : MonoBehaviour {


        Transform player;

        UnityEngine.AI.NavMeshAgent nav;


        void Awake ()
        {


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


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


        void Update ()
        {

            nav.SetDestination (player.position);
    
        }
    }

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

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

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

para que no se ralentice el videojuego y liberar memoria el script de abajo

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



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

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

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

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

using System;
using UnityEngine;
using Object = UnityEngine.Object;

namespace UnityStandardAssets.Utility
{
    public class ActivateTrigger : MonoBehaviour
    {
        // A multi-purpose script which causes an action to occur when
        // a trigger collider is entered.
        public enum Mode
        {
            Trigger = 0,    // Just broadcast the action on to the target
            Replace = 1,    // replace target with source
            Activate = 2,   // Activate the target GameObject
            Enable = 3,     // Enable a component
            Animate = 4,    // Start animation on target
            Deactivate = 5  // Decativate target GameObject
        }

        public Mode action = Mode.Activate;         // The action to accomplish
        public Object target;                       // The game object to affect. If none, the trigger work on this game object
        public GameObject source;
        public int triggerCount = 1;
        public bool repeatTrigger = false;


        private void DoActivateTrigger()
        {
            triggerCount--;

            if (triggerCount == 0 || repeatTrigger)
            {
                Object currentTarget = target ?? gameObject;
                Behaviour targetBehaviour = currentTarget as Behaviour;
                GameObject targetGameObject = currentTarget as GameObject;
                if (targetBehaviour != null)
                {
                    targetGameObject = targetBehaviour.gameObject;
                }

                switch (action)
                {
                    case Mode.Trigger:
                        if (targetGameObject != null)
                        {
                            targetGameObject.BroadcastMessage("DoActivateTrigger");
                        }
                        break;
                    case Mode.Replace:
                        if (source != null)
                        {
                            if (targetGameObject != null)
                            {
                                Instantiate(source, targetGameObject.transform.position,
                                            targetGameObject.transform.rotation);
                                DestroyObject(targetGameObject);
                            }
                        }
                        break;
                    case Mode.Activate:
                        if (targetGameObject != null)
                        {
                            targetGameObject.SetActive(true);
                        }
                        break;
                    case Mode.Enable:
                        if (targetBehaviour != null)
                        {
                            targetBehaviour.enabled = true;
                        }
                        break;
                    case Mode.Animate:
                        if (targetGameObject != null)
                        {
                            targetGameObject.GetComponent<Animation>().Play();
                        }
                        break;
                    case Mode.Deactivate:
                        if (targetGameObject != null)
                        {
                            targetGameObject.SetActive(false);
                        }
                        break;
                }
            }
        }


        private void OnTriggerEnter(Collider other)
        {
            DoActivateTrigger();
        }
    }
}




sábado, 8 de enero de 2022

Clonar enemigos con Unity.;Instantiation...;clonaciones;


 

Clonar enemigos con Unity.


Mirando tutoriales e visto como clonar personajes que fluyen continuamente de la nada en una escena de Unity, yo no tengo conocimientos para programar algo así, pero luego estuve pensando, jolín si clono proyectiles y consigo hacer disparos, pues uso el mismo sistema para personajes con movimiento incluido, y lo e conseguido aquí en el video podéis verlo, unos personajes prefabricados, con su rigidbody, ahora e de probar la persecución al player del videojuego…..le e de poner un NavMesh Agent y de preparar el terreno con un…


siguiendo este tema antes de poner un efecto de NavMesh Agent para que los clones persigan al player....... añado ejemplos de scripts sobre clonaciones y de Instantiation...

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

public class clonar2 : MonoBehaviour {


//public class clonar2 : MonoBehaviour {




// using UnityEngine;

//public class InstantiateExample : MonoBehaviour
// {
public GameObject prefab;

void Start()
{
for (int i = 0; i < 10; i++)
Instantiate(prefab, new Vector3(i * 2.0f, 0, 0), Quaternion.identity);
}
}

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

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

public class clonar3 : MonoBehaviour {

    // Use this for initialization
    //void Start () {
        
//    }
    
    // Update is called once per frame
    //void Update () {
        
    //}
//}



//public class Instantiation : MonoBehaviour {

    void Start() {
        for (int y = 0; y < 5; y++) {
            for (int x = 0; x < 5; x++) {
                GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                cube.AddComponent<Rigidbody>();
            //    cube.transform.position = new Vector3(x, y, 0);

                cube.transform.position = new Vector3 (-31f, -0.127f, -47f);


            }
        }
    }
}
-------------------------------------------------------------------------------------------------------------

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

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

public class clonar4 : MonoBehaviour {

    // Use this for initialization
//    void Start () {
       
//    }
    
    // Update is called once per frame
    //void Update () {
       
//    }
//}


public Transform brick;

void Start() {
    for (int y = 0; y < 5; y++) {
        for (int x = 0; x < 5; x++) {
        //    Instantiate(brick, new Vector3(x, y, 0), Quaternion.identity);

                Instantiate(brick, new Vector3(-31f, -0.127f, -47f), Quaternion.identity);

        }
    }
}
}

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

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

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

public class clonar5 : MonoBehaviour {
    public GameObject prefab;
    public int numberOfObjects = 20;
    public float radius = 5f;
    // Use this for initialization
    void Start () {

        for (int i = 0; 1 < numberOfObjects; i++) {
            float angle = i * Mathf.PI * 2 / numberOfObjects;
            Vector3 pos = new Vector3 (Mathf.Cos (angle), 0, Mathf.Sin (angle)) * radius;
            Instantiate (prefab, pos, Quaternion.identity);

        }
    }
//}
    // Update is called once per frame
//    void Update () {
       
    }
//}

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

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

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

    public class clonar11 : MonoBehaviour
    {


public GameObject prefab;
public int numberOfObjects = 20;
public float radius = 5f;

void Start()
{
    for (int i = 0; i < numberOfObjects; i++)
    {
        float angle = i * Mathf.PI * 2 / numberOfObjects;
        Vector3 pos = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * radius;
        Instantiate(prefab, pos, Quaternion.identity);
    }
}

}
-----------------------------------------------------------------------------------------------------------------

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

Los scripts de la parte inferior del video son los que e utilizado en el ejemplo del mismo video .

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

public class plumadaauno : MonoBehaviour {



        //public GameObject Sphere;
        // Use this for initialization




        public Rigidbody Sphere;
        public float velocidad = 1f;
        void disparador () {
            Rigidbody SphereClon = (Rigidbody) Instantiate (Sphere, transform.position, transform.rotation);
            SphereClon.velocity = transform.up * velocidad;

            //void Start () {

        }

        // Update is called once per frame
        void Update () {


            //    void Update () {
        }

        void OnTriggerEnter(Collider other) {
            //if (other.gameObject.CompareTag ("avismo")){
            //if (other.gameObject.CompareTag ("pepe")){
            if (other.gameObject.CompareTag ("pollo")){


                //if (Input.GetKey (KeyCode.Space)) {
                //Instantiate (Sphere);


                disparador ();///////////////////////////imbento yo


            }}
    }


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

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

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

public class disparadorautomaticocañonenemigo10peroa1 : MonoBehaviour {


        // Use this for initialization
        void Start () {

            //transform.rotation = Quaternion.Euler (0,45, 0);
        }

        // Update is called once per frame
        void Update () {
            // Es la rotacion de Angulos de Euler en grados.
            transform.Rotate (new Vector3 (0 * Time.deltaTime,1.1f, 0), Space.Self);


        }
    }




esta entrada seguirá en construcción a lo largo de esta quincena de enero del 2022.....es muy laboriosa, y ala vez que comento, estoy practicando y aprendiendo, 


algunos datos interesantes a continuación, estoy aprendiendo de este enlace

https://docs.unity3d.com/es/530/Manual/InstantiatingPrefabs.html

y una curiosidad, copiar a mano los scripts me cuesta un montón yo utilizo 



MonoDevelop - Unity 

 para hacer mis scripts, entonces uso la opción de seleccionar los textos de la web de los ejemplos de Unity.... copiar y pegar, y me encuentro que no los pega en el MonoDevelop de Unity, como también tengo y utilizo el

Microsoft Visual Studio para ver los scripts, lo abro pego aquí lo que me interesa y si aquí queda copiado pegado me lo admite..!!!!!......y desde aquí ,desde el visual studio ,buelbo a copiar y a pegar al que utilizo con Unity el MonoDevelop - Unity 

y así e resuelto este fastidioso problema, se que en realidad lo ideal seria copiar a mano los scripts pero es muy entretenido de tiempo y de vez en cuando creo se adelanta mas copiando y pegando...en fin son métodos de aprendizaje que utilizamos cada uno




jueves, 6 de enero de 2022

¿Como destruir enemigos con Unity?;

 

¿Como destruir enemigos con Unity?

Pongo divertido video de YouTube explicando el tema, divertido para mi, por que me estoy de paso promocionando, en plan que estupendo soy lo estoy haciendo todo genial...¡¡¡¡ja ja ja ja ja !!!!

(Se escuchan unos rujidos de fondo, pertenecen al juego cuando se ejecuta, pero no molestan excesivamente para comprender el video, solo duran unos momentos... )



Explico un problema que tenia con colisiones y destrucción de enemigos.

Creo esta resuelto con el siguiente script en C#….

ESCALAR

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

public class ESCALAR : MonoBehaviour {

    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {


        if (Input.GetKeyDown(KeyCode.M))// funciona pasito a pasito


        // En los 3 ejes estatico. 
        //transform.localScale = new Vector3 (0.5f * Time.deltaTime, 0.5f, 0.0f); 
        // En los 3 ejes Dinámico.
//    transform.localScale += new Vector3 (0.5f * Time.deltaTime, 0.0f, 0.0f); 
        // En un solo eje Dinámico.
        transform.localScale += Vector3.right * 77* Time.deltaTime;



        if (Input.GetKeyUp(KeyCode.M))// funciona pasito a pasito




            transform.localScale -= Vector3.right *77* Time.deltaTime;

        
    }
}



al apretar la tecla “m” la esfera que tiene el hombre lobo se escala y al tocar el Trigger activado de la victima produce su aniquilación, esta asu vez tiene el script de “activate Trigger” que hace el cambio de personajes de vivo a aniquilado.




using System;
using UnityEngine;
using Object = UnityEngine.Object;

namespace UnityStandardAssets.Utility
{
    public class ActivateTrigger : MonoBehaviour
    {
        // A multi-purpose script which causes an action to occur when
        // a trigger collider is entered.
        public enum Mode
        {
            Trigger = 0,    // Just broadcast the action on to the target
            Replace = 1,    // replace target with source
            Activate = 2,   // Activate the target GameObject
            Enable = 3,     // Enable a component
            Animate = 4,    // Start animation on target
            Deactivate = 5  // Decativate target GameObject
        }

        public Mode action = Mode.Activate;         // The action to accomplish
        public Object target;                       // The game object to affect. If none, the trigger work on this game object
        public GameObject source;
        public int triggerCount = 1;
        public bool repeatTrigger = false;


        private void DoActivateTrigger()
        {
            triggerCount--;

            if (triggerCount == 0 || repeatTrigger)
            {
                Object currentTarget = target ?? gameObject;
                Behaviour targetBehaviour = currentTarget as Behaviour;
                GameObject targetGameObject = currentTarget as GameObject;
                if (targetBehaviour != null)
                {
                    targetGameObject = targetBehaviour.gameObject;
                }

                switch (action)
                {
                    case Mode.Trigger:
                        if (targetGameObject != null)
                        {
                            targetGameObject.BroadcastMessage("DoActivateTrigger");
                        }
                        break;
                    case Mode.Replace:
                        if (source != null)
                        {
                            if (targetGameObject != null)
                            {
                                Instantiate(source, targetGameObject.transform.position,
                                            targetGameObject.transform.rotation);
                                DestroyObject(targetGameObject);
                            }
                        }
                        break;
                    case Mode.Activate:
                        if (targetGameObject != null)
                        {
                            targetGameObject.SetActive(true);
                        }
                        break;
                    case Mode.Enable:
                        if (targetBehaviour != null)
                        {
                            targetBehaviour.enabled = true;
                        }
                        break;
                    case Mode.Animate:
                        if (targetGameObject != null)
                        {
                            targetGameObject.GetComponent<Animation>().Play();
                        }
                        break;
                    case Mode.Deactivate:
                        if (targetGameObject != null)
                        {
                            targetGameObject.SetActive(false);
                        }
                        break;
                }
            }
        }


        private void OnTriggerEnter(Collider other)
        {
            DoActivateTrigger();
        }
    }
}