miércoles, 23 de septiembre de 2020

Detalles interesantes para unity

Detalles interesantes para unity 

 

Detalles interesantes para unity trucos si queremos decirlo asi, para crear gameobjets o graficos en 3d del juego y compaginarlos con otros elementos, objetos que tenemos en el juego.....


Pondré de ejemplo el videojuego que estoy creando.....


https://gamejolt.com/games/YELLOW_AIRPLANES_NO/527317

https://gamejolt.com/games/YELLOW_AIRPLANES_NO/527317 

 😆😆😆😆😆😆😆😆😆😆😆😆😆😆😆😆😆 😆😆😆😆😆😆😆😆😆😆😆

 niveles-de-yellowairplanesno527317.html 

😆😆😆😆😆😆😆😆😆😆😆😆😆😆😆😆😆😆😆😆😆😆😆😆 😆😆😆😆




Este videojuego tiene tres niveles o etapas de momento ….explicare la ultima que estoy haciendo, hay un detalle que e aprendido hace muy poco, en el tercer nivel llamado......”ROBOTICA”

construyo una ambientación , futurista, elementos de arquitectura metálicos.....esta muy verde aun pero se puede jugar el juego, jugavilidad tiene aunque falta pulir lo y trabajarlo por supuesto.......


Bueno al grano que me estoy enrollando, en un entorno montañoso, creo unas estructuras metálicas y dentro de ellas , hay unos humanoides robots que van corriendo dentro de ellas entrando y saliendo continuamente y a la vez van realizando disparos, disparos al aire con intención de derribar cual quier cosa que se acerque,



abuelo dispositivo (12), en la ilustración que pongo, una captura de pantalla destaca este elemento “


 

“abuelo dispositivo (12)”, intentare explicarlo lo mejor que sepa, si beis la captura de pantalla desde aquí parten el resto de elementos del juego que son “padres e hijos”......




En la segunda captura de pantalla, se ve en azul lo que seria el padre, y ala vez el hijo, de los elementos, todo parte de , “abuelo dispositivo (12)............




¿Y para que sirve esto que estoy explicando? ¿Y como lo ago?

Es muy fácil, para crear muchas estructuras con enemigos dentro dando vueltas, sin tener que hacerlos de uno en uno, que no se acavaria nunca de hacer.




El primer paso , no hay mas remedio, de uno en uno, un elemento el robot, otro elemento el disparador del robot, que por cierto se pone de hijo del robot el robot es el padre, otro elemento labarra alargada que va girando por sript en c# esta asu vez es padre del robot que da vueltas gracias a ella, otros elementos , echas también de una en una pieza, la estructura metálica de varias piezas,


Cuando esto se hace funcionar y estamos mas o menos satisfechos del resultado y queremos repetirlo muchas veces para incorporarlo en el videojuego....¿como se hace?


Yo lo e echo seleccionando todos los elementos que quiero repetir a la vez y arrastrándolos aun objeto nuevo, un cubo en este caso, el cubo se llama......“abuelo dispositivo (12)”........


Ahora podreis copiar ese cubo con nombre ..“abuelo dispositibo (12)”....y duplicarlo infinidad de veces para ponerlo en el videojuego que agais.............podreis duplicar todo lo que deseeis y ahorrar muchisimo trabajo.


 

Solo un ultimo detalle se os deformaran los objetos las primeras veces que probéis de hacer esto, pero con practicas y pruebas, yo me incluyo porque aun mepasa lo iréis corrigiendo todo poco a poco.

viernes, 18 de septiembre de 2020

C# UNITY

C# PARA UNITY PARA REINICIAR UN JUEGO

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

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;/// <summary>
/// ////////////////////////7777777777777777777777777puestoyo ahoraaaaaaaaa sin esto no ba
/// </summary>
public class reiniciojuego : MonoBehaviour {



        public Text contador1;
        public Text fin1;
        private float tiempo = 8f;
        // Use this for initialization
        void Start () {
            contador1.text = " " + tiempo;
            fin1.enabled = false;




        }

        // Update is called once per frame
        void Update ()
        {
            tiempo -= Time.deltaTime;
            contador1.text = " " + tiempo.ToString ("f0");
            if (tiempo <= 0) {
                contador1.text = "0";
                fin1.enabled = true;









            {
//void OnTriggerEnter(Collider other) {
    //if (other.gameObject.CompareTag ("ogri2 (1)CAMPEONNNNNNNNNNNNNNNNNNN")){








Destroy (gameObject, 0.0f);

{

//Application.LoadLevel (1); ESTE ES EL ORIGINALLLLLLL

Application.LoadLevel (0);





            }
        }
    }
}

}

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

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

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

OTRO EJEMPLO PARA REINICIAR UN JUEGO

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

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

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;/// <summary>
/// ////////////////////////7777777777777777777777777puestoyo ahoraaaaaaaaa sin esto no ba
/// </summary>
public class reiniciojuegotankes : MonoBehaviour {



        public Text contador1;
        public Text fin1;
        private float tiempo = 4f;
        // Use this for initialization
        void Start () {
            contador1.text = " " + tiempo;
            fin1.enabled = false;




        }

        // Update is called once per frame
        void Update ()
        {
            tiempo -= Time.deltaTime;
            contador1.text = " " + tiempo.ToString ("f0");
            if (tiempo <= 0) {
                contador1.text = "0";
                fin1.enabled = true;









            {
//void OnTriggerEnter(Collider other) {
    //if (other.gameObject.CompareTag ("ogri2 (1)CAMPEONNNNNNNNNNNNNNNNNNN")){








Destroy (gameObject, 0.0f);

{

//Application.LoadLevel (1); ESTE ES EL ORIGINALLLLLLL

Application.LoadLevel (0);





            }
        }
    }
}

}

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

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

PARA MOVIMIENTO DE UN OBJETO......EN ESTE CASO DE UNOS AVIONES

https://gamejolt.com/games/YELLOW_AIRPLANES_NO/527317

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

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

public class avionvuelasolo : MonoBehaviour {


    public float moveSpeed = 110f;
    public float turnSpeed = 50f;


    void Update ()
    {














        //if (Input.GetKey(KeyCode.W))////funciona contantemente al apretar W mayusculas a de ser
        //if (Input.GetKeyDown(KeyCode.W))// funciona pasito a pasito
        //if(Input.GetKey(KeyCode.UpArrow))
            transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);






        if (Input.GetKey(KeyCode.W))////funciona contantemente al apretar W mayusculas a de ser
        //if (Input.GetKeyDown(KeyCode.W))// funciona pasito a pasito
        //if(Input.GetKey(KeyCode.UpArrow))
            transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);




        if (Input.GetKey(KeyCode.S))////funciona contantemente al apretar W mayusculas a de ser
        //if(Input.GetKey(KeyCode.DownArrow))
            transform.Translate(-Vector3.forward * moveSpeed * Time.deltaTime);


        if (Input.GetKey(KeyCode.A))////funciona contantemente al apretar W mayusculas a de ser
        //if(Input.GetKey(KeyCode.LeftArrow))
            transform.Rotate(Vector3.up, -turnSpeed * Time.deltaTime);

        if (Input.GetKey(KeyCode.D))////funciona contantemente al apretar W mayusculas a de ser

        //if(Input.GetKey(KeyCode.RightArrow))
            transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);
    }
}

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

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

PARA GIROS DE UN OBJETO SOBRE SIMISMO

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

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

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

public class aspa : 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 (33 * Time.deltaTime, 0, 0), Space.Self);


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

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

PARA LIBERAR MEMORIA BORRANDO OBJETOS

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

 using UnityEngine;
using System.Collections;
using UnityEngine;
public class BORRAMIBALA : MonoBehaviour {
    public float Destroy = 2f;
    // Use this for initialization
    void Start () {
       
    }
    
    
    
    
    void OnCollisionEnter (){
       
        Destroy (gameObject, 3.30f);
       
       
       
       
       
    }
}

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

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

OTRO EJEMPLO DE LIBERAR MEMORIA DE OBJETOS POR TIEMPO EN UN JUEGO

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

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

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

PARA CONTROLAR OBJETOS CON EL MOUSE CON EL RATON...

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

using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

namespace UnityStandardAssets.Utility
{
    public class SimpleMouseRotator : MonoBehaviour
    {
        // A mouselook behaviour with constraints which operate relative to
        // this gameobject's initial rotation.
        // Only rotates around local X and Y.
        // Works in local coordinates, so if this object is parented
        // to another moving gameobject, its local constraints will
        // operate correctly
        // (Think: looking out the side window of a car, or a gun turret
        // on a moving spaceship with a limited angular range)
        // to have no constraints on an axis, set the rotationRange to 360 or greater.
        public Vector2 rotationRange = new Vector3(70, 70);
        public float rotationSpeed = 10;
        public float dampingTime = 0.2f;
        public bool autoZeroVerticalOnMobile = true;
        public bool autoZeroHorizontalOnMobile = false;
        public bool relative = true;
        
        
        private Vector3 m_TargetAngles;
        private Vector3 m_FollowAngles;
        private Vector3 m_FollowVelocity;
        private Quaternion m_OriginalRotation;


        private void Start()
        {
            m_OriginalRotation = transform.localRotation;
        }


        private void Update()
        {
            // we make initial calculations from the original local rotation
            transform.localRotation = m_OriginalRotation;

            // read input from mouse or mobile controls
            float inputH;
            float inputV;
            if (relative)
            {
                inputH = CrossPlatformInputManager.GetAxis("Mouse X");
                inputV = CrossPlatformInputManager.GetAxis("Mouse Y");

                // wrap values to avoid springing quickly the wrong way from positive to negative
                if (m_TargetAngles.y > 180)
                {
                    m_TargetAngles.y -= 360;
                    m_FollowAngles.y -= 360;
                }
                if (m_TargetAngles.x > 180)
                {
                    m_TargetAngles.x -= 360;
                    m_FollowAngles.x -= 360;
                }
                if (m_TargetAngles.y < -180)
                {
                    m_TargetAngles.y += 360;
                    m_FollowAngles.y += 360;
                }
                if (m_TargetAngles.x < -180)
                {
                    m_TargetAngles.x += 360;
                    m_FollowAngles.x += 360;
                }

#if MOBILE_INPUT
            // on mobile, sometimes we want input mapped directly to tilt value,
            // so it springs back automatically when the look input is released.
            if (autoZeroHorizontalOnMobile) {
                m_TargetAngles.y = Mathf.Lerp (-rotationRange.y * 0.5f, rotationRange.y * 0.5f, inputH * .5f + .5f);
            } else {
                m_TargetAngles.y += inputH * rotationSpeed;
            }
            if (autoZeroVerticalOnMobile) {
                m_TargetAngles.x = Mathf.Lerp (-rotationRange.x * 0.5f, rotationRange.x * 0.5f, inputV * .5f + .5f);
            } else {
                m_TargetAngles.x += inputV * rotationSpeed;
            }
#else
                // with mouse input, we have direct control with no springback required.
                m_TargetAngles.y += inputH*rotationSpeed;
                m_TargetAngles.x += inputV*rotationSpeed;
#endif

                // clamp values to allowed range
                m_TargetAngles.y = Mathf.Clamp(m_TargetAngles.y, -rotationRange.y*0.5f, rotationRange.y*0.5f);
                m_TargetAngles.x = Mathf.Clamp(m_TargetAngles.x, -rotationRange.x*0.5f, rotationRange.x*0.5f);
            }
            else
            {
                inputH = Input.mousePosition.x;
                inputV = Input.mousePosition.y;

                // set values to allowed range
                m_TargetAngles.y = Mathf.Lerp(-rotationRange.y*0.5f, rotationRange.y*0.5f, inputH/Screen.width);
                m_TargetAngles.x = Mathf.Lerp(-rotationRange.x*0.5f, rotationRange.x*0.5f, inputV/Screen.height);
            }

            // smoothly interpolate current values to target angles
            m_FollowAngles = Vector3.SmoothDamp(m_FollowAngles, m_TargetAngles, ref m_FollowVelocity, dampingTime);

            // update the actual gameobject's rotation
            transform.localRotation = m_OriginalRotation*Quaternion.Euler(-m_FollowAngles.x, m_FollowAngles.y, 0);
        }
    }
}
---------------------------------------------------------------------------------------------------------------------------

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

PARA BORRAR OBJETOS , EN ESTE CASO AL PULSAR TECLA "K"

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

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

public class nivelfacil : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }



    void Update ()
    {



    if (Input.GetKey(KeyCode.K))

    //void OnCollisionEnter (){

        Destroy (gameObject, 0.00f);




    }
}

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

----------BALA ENEMIGA PROBOCA AL COLISIONAR PLAYER REINICIAR EL VIDEOJUEGO-------------------------------------------------------------------------------------------------------------

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

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

public class BALAENEMIGAMEREINICIAPORTAG : MonoBehaviour {


    //public float distancePerSecond;//////IMBENTADO




    //public float Destroy = 0.2f;
    // Use this for initialization
    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);




        }
    }
}

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

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

 ----------------BORRA UN GAMEOBJECT AL PRESIONAR DOS TECLAS AL MISMO TIEMPO

 

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

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

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

public class borraalpresionardosteclasalavez : MonoBehaviour {

        // Use this for initialization
        void Start () {

        }



        void Update ()
        {



            if ((Input.GetKey(KeyCode.W)) &&(Input.GetKey(KeyCode.E)))

                //void OnCollisionEnter (){

                Destroy (gameObject, 0.00f); 



        }
    }

 

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

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

 ------------------------------------- CAMBIA LAS COORDENADAS DE UN GAMEOBJECT AL SER COLISIONADO--------------------------------------------------------------------------------------------

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

 

 

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

public class cambiacordenadasalcolisionarportac : MonoBehaviour {


    //public float distancePerSecond;//////IMBENTADO




        //public float Destroy = 0.2f;
        // Use this for initialization
        void Start () {

        }




        //void OnCollisionEnter (){


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


            if (collision.gameObject.tag == "balaamericano") {
                //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


        


            }
        }
    }

 

 

 

 

 

 

 

 

 

 

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

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

 DISPARANDO RAFAGAS DE AMETRALLADORA AL MANTENER PULSADA UNA TECLA O UN BOTON DEL RATON

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

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

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

public class launchermasvelocidad : MonoBehaviour {


        public Rigidbody projectile;
        public Rigidbody explosiveProjectile;
        public float launchspeed = 50;
        public bool useExplodingProjectiles = false;

        private float _LaunchDelayTime = 0.0f;

        public int stackSize = 60;            
        public Transform launchHole1;
        public Transform launchHole2;

        private Stack _Projectiles;
        private Stack _ExplosiveProjectiles;
        private Transform _myTransform;

        // Use this for initialization
        void Start ()
        {
            _myTransform = transform;
            _Projectiles = new Stack();
            if(useExplodingProjectiles)
            {
                _ExplosiveProjectiles = new Stack();
            }

            for(int i = 0; i <  stackSize; i++)
            {
                Rigidbody tr = Instantiate (projectile, _myTransform.position, _myTransform.rotation) as Rigidbody;
                PushProjectile(tr);

                if(useExplodingProjectiles)
                {
                    Rigidbody rr = Instantiate (explosiveProjectile, _myTransform.position, _myTransform.rotation) as Rigidbody;
                    PushExplosiveProjectile(rr);
                }
            }
        }

        // Update is called once per frame
        void Update ()
        {
            if(_Projectiles.Count > 0)
            {
                if(Time.time > _LaunchDelayTime)
                {    




                    if (Input.GetButton ("Fire1")) ////ametralladora
                        //    if (Input.GetButtonDown ("Fire1")) original tiro a tiro

                    {
                        Rigidbody tr = PopProjectile();
                        tr.gameObject.SetActive(true);
                        tr.transform.position = launchHole1.position;
                        tr.transform.rotation = launchHole1.rotation;
                        tr.velocity = transform.TransformDirection (Vector3.forward * launchspeed);

                        tr = PopProjectile();
                        tr.gameObject.SetActive(true);
                        tr.transform.position = launchHole2.position;
                        tr.transform.rotation = launchHole2.rotation;
                        tr.velocity = transform.TransformDirection (Vector3.forward * launchspeed);

                        _LaunchDelayTime = Time.time + 0.1f;
                    }
                }    
            }

            if(useExplodingProjectiles)
            {
                if(_ExplosiveProjectiles.Count > 0)
                {
                    if(Time.time > _LaunchDelayTime)
                    {    
                        if (Input.GetButtonDown ("Fire2")) 
                        {
                            Rigidbody tr = PopExplosiveProjectile();
                            tr.gameObject.SetActive(true);
                            tr.transform.position = launchHole1.position;
                            tr.transform.rotation = launchHole1.rotation;
                            tr.velocity = transform.TransformDirection (Vector3.forward * launchspeed);

                            tr = PopExplosiveProjectile();
                            tr.gameObject.SetActive(true);
                            tr.transform.position = launchHole2.position;
                            tr.transform.rotation = launchHole2.rotation;
                            tr.velocity = transform.TransformDirection (Vector3.forward * launchspeed);

                            _LaunchDelayTime = Time.time + 0.5f;
                        }
                    }    
                }
            }
        }

        public void PushProjectile(Rigidbody x)
        {
            x.gameObject.SetActive(false);
            _Projectiles.Push(x);
        }

        public Rigidbody PopProjectile()
        {
            return (Rigidbody)_Projectiles.Pop();
        }

        public void PushExplosiveProjectile(Rigidbody x)
        {
            x.gameObject.SetActive(false);
            _ExplosiveProjectiles.Push(x);
        }

        public Rigidbody PopExplosiveProjectile()
        {
            return (Rigidbody)_ExplosiveProjectiles.Pop();
        }
    }


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

------SCRIPT DE C# PARA CREAR UNA CAMARA UN GAMEOBJECT UN CUBO AL QUE ASOCIAMOS UNA CAMARA Y QUE LA ACTIVAMOS AL APRETAR LA TECLA -D-

------https://videojuegosenlineaasaco4.blogspot.com/p/script-de-c-para-crear-una-camara-un.html---------------------------------------------------------------

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


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

public class CREACAMARAALAPRETARAOD : MonoBehaviour
{

    public GameObject retra, pico;

    void Update()
    {
        // if (Input.GetKey(KeyCode.D))

        if (Input.GetKeyDown(KeyCode.D))
        // if (Input.GetButton(KeyCode.D))

        //if (Input.GetButton("Fire3") )
            


            //  if (Input.GetKeyDown(KeyCode.Alpha2))//////original
            {
                retra.SetActive(true);//original
                pico.SetActive(false);//original
 

        }



           if (Input.GetKeyDown(KeyCode.A))
          {
          retra.SetActive(false);
        pico.SetActive(true);

    }


        if (Input.GetKeyDown(KeyCode.W))
        {
            retra.SetActive(false);
            pico.SetActive(true);

        }


        if(Input.GetKeyDown(KeyCode.S))
        {
            retra.SetActive(false);
            pico.SetActive(true);

        }

    }

}

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

😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃😃

C# PARA UNITY

😁😁😁😁😁😁😁😁😁😁😁😁😁😁😁