UNITY 3D REFERENCE SCRIPTING - Netsitesnetsites.mx/Unity3dTutorials/FuncionesScriptBasicas.pdf ·...
Transcript of UNITY 3D REFERENCE SCRIPTING - Netsitesnetsites.mx/Unity3dTutorials/FuncionesScriptBasicas.pdf ·...
By: Deodato Pechir.
UNITY 3D REFERENCE SCRIPTING
INDICE DINÁMICO – REFERENCIA DE SCRIPTING
MENU:
VARIABLES.
SCRIPTING BASICOS (if, switch, while, for).
TIPO DE FUNCIONES UNITY.
INPUT CONTROLLERS.
TRANSFORM MOVIMIENTO.
TRANSFORM ROTACION/ESCALA.
FUNCIONES BASICAS.
• MIRAR HACIA UN PUNTO.
• GIRAR CON SUAVIDAD HACIA UN PUNTO.
• BUSCAR GAMEOBJECTS/GETCOMPONENTS.
• COMPONENTES ACTIVACION / DESACTIVAR.
• TIME.
• PAUSA GAME.
• GAMEOBJECT DESACTIVAR.
• RANDOM.
• INSTANCIAR PREFABS.
• DESTRUIR OBJETOS.
• LOCAL TO WORLD SPACE / INVERSE. • VECTOR3 DISTANCIA/ANGULO.
• DEBUG.
• PHYSICS. • SCREEN.
• APLICATIONS.
• AUDIO.
• GIZMOS. • COMPARTIR VARIABLES/FUNCIONES ENTRE SCRIPTS SOBRE EL MISMO GAMEOBJECT.
• ENUM - VARIABLE LISTA. • MATERIALES.
RAYCASTING.
TRIGGERS.
COLLISION.
DYNAMICS.
RAGDOLL.
SCREENPONTRAY (CLICK & MOVE & ROTATE).
SAVE & LOAD SCENE VALUES. ANIMATION.
GUI: TEXTURE / TEXT.
YIELD / CORRUTINAS.
INVOKE / CORRUTINAS.
Nota: Si quieres regresar al Índice haz click sobre el Cubo en la parte superior derecha de cada página
3
www.3dboxweb.com
VARIABLES:
var DeoValor1 : String; //Textos
var DeoValor2 : float; // Valores enteros
var DeoValor3 : int; //Valores decimales
var DeoValor4 : boolean; //Valores boleanos 0, 1,true, false.
var DeoValor5 : GameObject; //Objetos dentro de la escena.
var DeoValor6 : Transform; //Valores de transform de un GameObject (mover, rotar, escalar).
var DeoValor7 : Rigidbody; //Valor de un GameObject de tipo rigidbody.
var DeoValor8 : Collision; //Valor de un GameObject cuando Colisiona.
var DeoValor9 : AudioClip; //Valor de un GameObject de tipo sonido.
var DeoValor10 : ParticleEmitter; //Valor de un GameObject de tipo partículas.
var DeoValor11 : Texture2D; //Valor de una Textura.
var DeoValor12 : Camera; //Valor de un GameObject de tipo Cámara.
var DeoValor13 : Light; //Valor de un GameObject de tipo Luces.
var DeoValor14 : CharacterController; //Valor de un GameObject de tipo Control de personaje (1ra y 3ra Persona).
var DeoValor15 : Color; //Valor de cambio/asignación de color en una variable.
var DeoValor16 : Material; //Valor de un GameObject de tipo Material.
var DeoValor17 : AnimationClip; //Valor de un GameObject de tipo Animación (Clips).
var DeoValor18 : Renderer; // Valor de un GameObject de tipo Render materiales/color/visible, etc.
var DeoValor[] : Cualquier Tipo; // Valor para crear / Eliminar slots para almacenar variables del tipo de variable asignada.
Variables Privadas: No permite publicarse dentro del Inspector.
private var DeoValor : String = "Hola todos";
Variables Públicas: Permite comunicarse entre los Scripts del mismo GameObject u otros GameObjects (Consume mas memoria):
static var DeoValor : String = "Hola todos";
4
www.3dboxweb.com
SCRIPTS BÁSICOS:
CONDICIONANTES:
if (Valor1 comparador Valor2){
//acción
}else {
//otra acción
}
if (Valor1 comparador Valor2){
//acción A
}else if {
//Acción B
} else {
//Otra Acción
}
Comparadores:
'>' A es mayor que B
'<' A es Menor que B
'==' A es igual a B
'!=' A No es igual a B
'>=' A Es mayor o igual a B
'<=' A Es menor o igual a B
&& Para 2 o más comparaciones.
|| Para una u otra comparación.
SWITCH:
var CambioArma = "A";
switch (CambioArma){
case "A":
Debug.Log ("Cambio a Metralleta");
break; // termina la acción en este punto
case "B":
Debug.Log ("Cambio a Lanza Misiles");
break; // termina la acción en este punto
default: // si no hay ningún caso, se ejecuta el de default (nada).
break; // termina la acción en este punto
}
5
www.3dboxweb.com
WHILE:
function Start () {
var Valor : int = 0; // variable para usar en el loop.
// Si es igual a 10 o mayor se cumpla el loop.
while (Valor <= 10) {
// Se hace aquí la acción que queremos repetir.
Debug.Log("Cantidad: " + Valor);
// Agregamos el valor de 1, cada q se hace un loop.
Valor ++;
}
}
FOR:
for (var Valor : int = 0; Valor <= 10; Valor ++) {
// Se hace aquí la acción que queremos repetir.
Debug.Log ("Cantidad" + Valor);
}
FOR IN & ARRAY:
// Creamos un arreglo para almacenar varios valores.
var nombres = new Array();
//arreglo y sus valores
nombres[0] = "Juan";
nombres[1] = "Pedro";
nombres[2] = "Jesús";
nombres[3] = "Martin";
// obtener los valores del arreglo meterlos en una variable
function Start () {
for (var Imprimir in nombres){
Debug.Log (Imprimir);
}
// Creamos un arreglo para almacenar varios valores.
var nombres = new Array("Juan", " Pedro ", " Jesús ", " Martin ");
// obtener los valores del arreglo meterlos en una variable
function Start () {
for (var Imprimir in nombres){
Debug.Log (Imprimir);
}
6
www.3dboxweb.com
TIPO DE FUNCIONES UNITY:
EVENTOS ESCENAS:
function Update () {} – Es llamado cada frame.
function LateUpdate () {} – Es llamado cada frame. Si el “Behaviour” esta “activado”.
function FixedUpdate () {} – Es llamado cada Fixed frame (Físicas).
function Awake() {} – Es llamado cuando una instancia de script se está cargado (antes).
function Start () {} – Es llamado al inicio de la escena cuando esta se haya cargado (después).
function Reset () {} – Reinicia los valores por default.
EVENTOS PARA MOUSE:
function OnMouseEnter () {} – Es llamado cuando el mouse Entra en el GUIElement o un Collider.
function OnMouseOver () {} – Es llamado cada frame cuando el mouse esta Encima del GUIElement o Collider.
function OnMouseExit () { } – Es llamado cuando el mouse ya no está más sobre GUIElement o Collider.
function OnMouseDown () {} – Es llamado cuando el mouse Presiono botón sobre un GUIElement o Collider.
function OnMouseUp () } – Es llamado cuando el mouse Soltó el botón sobre un GUIElement o Collider.
function OnMouseDrag () {} – Es llamado cuando el mouse Presiono botón sobre un GUIElement o Collider y aun continua presio.
EVENTOS TRIGGERS:
function OnTriggerEnter () {} – Es llamado cuando el Collider u otros entran en el Trigger.
function OnTriggerExit() {} –Es llamado cuando el Collider u otros han parado de tocar en el Trigger.
function OnTriggerStay () } – Es llamado 1 vez por Frame por cada Collider u otros que están tocando al Trigger.
EVENTOS COLISIONADORES_
function OnCollisionEnter () {} – Es llamado cuando este Collider/rigidbody a comenzado a tocar otro rigidbody/Collider.
function OnCollisionExit() {} – Es llamado cuando este Collider/rigidbody ha dejado de tocar a otro Collider/rigidbody.
function OnCollisionStay() {} – Es llamado 1 vez por frame cada que este Collider/rigidbody está tocando otro Collider/rigidbody.
EVENTOS VISIBLES:
function OnBecameVisible () {} – Es llamado cuando el Render se ha cambiado a Visible por cualquier cámara.
function OnBecameInvisible() {} – Es llamado cuando el Render se ha cambiado a Invisible por cualquier cámara.
7
www.3dboxweb.com
TRASNFORM MOVIMIENTO:
Vector.zero (0,0,0) | Vector.one (1,1,1) | Vector.up (0,1,0) | Vector.forward (0,0,1) | Vector.right (1,0,0,)
TRANSFORM POSITION:
// Vector3.
transform.position = Vector3 (0, 0, 0); -- transform.position = Vector3.zero;
// Vector1.
transform.position.X = 10; | transform.position.Y = 10; | transform.position.Z = 10;
// Una manera de usar el Vector3 = forward (eje azul), up (eje verde), right (eje rojo).
function Update() {
transform.position += transform.forward/up/right * 0.2 *Time.deltaTime;
}
TRANSFORM TRANSLATE:
function Update() {
// Mueve al objeto hacia arriba en el "world space" 1 unidad/segundo.
transform.Translate (Vector3.up * 0.2 * Time.deltaTime, Space.Self);
}
TRANSFORM LINEAR INTERPOLATE:
var Smooth : float = 1;
function Update() {
//OPCION 1: no permite que exceda la velocidad, así llega al target asignado.
transform.position = Vector3.Lerp (transform.position, Vector3 (0, 0, 0), Time.deltaTime * Smooth);
//OPCION 2: Puede exceder la velocidad y salir del target asignado.
transform.position = Vector3.MoveTowards (transform.position, Vector3 (0, 0, 0), Time.deltaTime * Smooth);
}
ANIMACIÓN LINEAL PINGPONG.
var Velocidad : float ; var Distancia : float; var Altura : float;
function Update () {
transform.position.y = Mathf.PingPong(Time.time * Velocidad, Distancia) + Altura;
}
8
www.3dboxweb.com
TRANSFORM ROTACIÓN / ESCALA:
TRANSFORM ROTATE (eulerAngles:Vector3, Space:Space.World/Self):
function Update() {
// Pone al objeto a rotar en el eje de las X 20 grados/segundo.
transform.Rotate (Vector3(20 * Time.deltaTime, 0, 0), Space.Self);
}
TRANSFORM ROTATE AROUND (point:Vector3, Axis:Vector3, angle:float):
function Update() {
// Pone al objeto en un solo eje a girar en su origen a 20 grados/segundo [Vector3.zero = Vector3 (0, 0, 0)].
transform.RotateAround (Vector3(1,0,0), Vector3.up, 20 * Time.deltaTime);
}
TRANSFORM ROTATE INTERPOLATE (from:Quaternion, to:Quaternion, t:float):
var to : Transform;
var GirarVelocidad = 1.5;
function Update() {
transform.rotation =Quaternion.Slerp (from.rotation, to.rotation, Time.deltaTime * GirarVelocidad);
}
TRANSFORM SCALE (localScale:Vector3):
function Update () {
//escalara al objeto -0.5 unidades/segundo.
transform.localScale -= Vector3 (0.5 * Time.deltaTime, 0, 0); / transform.localScale.x += 0.02;
}
9
www.3dboxweb.com
INPUT/GET CONTROLLERS:
INPUT - GET AXIS:
function Update () {
// Mueve al objeto en horizontal/vertical del axis del inputs, agrega el valor del axis.
transform.Translate (Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical"));
Debug.Log (Input.GetAxis ("Horizontal"));
Debug.Log (Input.GetAxis ("Vertical"));
}
INPUT - GETBUTTON:
function Update () {
if (Input.GetButtonDown ("NOMBRE_INPUT")){
//acción
}
}
INPUT - MOUSEWHEEL:
var mouseWheel : float = Input.GetAxis ("Mouse Wheel"); //Input: Sensibility: 1, Type: Mouse Movements, Axis: 3rd Axis Scroll.
GETMOUSE BUTTON:
function Update () {
if ( Input.GetMouseButtonDown (0) ){ // 0 = Izquierdo, 1 = Derecho, 2 =Scroll
//acción
}
}
GETKEY - STRINGS:
function Update () {
if ( Input.GetKeyDown ("space") ){
}
}
GETKEY - KEYCODE:
function Update () {
if ( Input.GetKeyDown (KeyCode.Space) ){
//acción
}
}
10
www.3dboxweb.com
FUNCIONES BÁSICAS:
MIRAR HACIA UN PUNTO.
transform.LookAt (VariableTransform);
GIRAR CON SUAVIDAD HACIA UN PUNTO.
var target : Transform;
var Angulo = Quaternion.LookRotation (target.position - transform.position, Vector3.up); transform.rotation = Quaternion.Slerp (transform.rotation, Angulo, Time.deltaTime * 0.5);
//Rotación en un solo eje siguiendo a un objeto en los 3 ejes.
transform.rotation.y = Quaternion.LookRotation(target.position - transform.position)[1];
transform.LookAt ( Vector3 (target.position.x, 0, target.position.z) * .1* Time.deltaTime );
BUSCAR GAMEOBJECTS / GETCOMPONENTS.
vGameObject = GameObject.FindWithTag ("Nom breTag"); // Buscar objetos dinámicamente en la escena por tag.
vGameObject = GameObject.Find ("NombreGameObject"); // Buscar objetos dinámicamente en la escena por nombre.
vGameObject.GetComponent("NombreScript").variableOfuncion(); // Conectarse al script de otro gameObject de la escena.
COMPONENTES ACTIVACION / DESCTIVAR.
light.enabled = true / false; // Luces
Camera.enabled = true / false; // Cámaras
renderer.enabled = false; // Render
collider.isTrigger = true; // Colisionar
TIME.
Time.time // Se mete en una variable y se captura el tiempo cuando se ejecuta.
Time.deltaTime // Regula la velocidad del "transform" en frames/segundos
Time.smoothDeltaTime // Regula la velocidad del "transform" en frames/segundos suavemente.
Time.realtimeSinceStartup // El tiempo real en segundos desde que el juego inicio.
11
www.3dboxweb.com
PAUSE GAME. Time.timeScale = 0 / 1; // Pausa toda la acción del juego 0: Pausa, 1: Reanudar.
AudioListener.pause = true / false; // Pausa el audio que escucha el listener de la cámara. GAMEOBJECT DESCTIVAR.
gameObject.SetActiveRecursively (false/true); // Desactiva por completo al GameObjeto y sus Child así como scripts. RANDOM. Random.Range (); // Creación de Random entre un Mínimo y Máximo.
Random.Rotation (); // Creación de Random en rotación.
INSTANCIAR PREFABS.
var Jugador : GameObject;
Instantiate (VariableGameObject, Posicion, Rotacion); -- Instantiate (VariableGameObject, transform.position, transform.rotation); DESTUIR OBJETOS.
Destroy (gameObject); / Destroy (gameObject, 1); //Destruir GameObject / por tiempo
Destroy (this); // Destruir el script de la instancia.
Destroy (rigidbody); // Destruye el Rigidbody del GameObject.
LOCAL TO WORLD SPACE / INVERSE
Transform.TransformDirection (Vector3.forward/right/up); //Cambia de Local a world space X,Y,Z.
Transform.TransformInverseDirection (Vector3.forward/right/up); //Cambia de World a Local space X,Y,Z.
VECTOR3 DISTANCIA/ANGULO.
var Jugador : Transform;
var Distancia = Vector3.Distance (Jugador.position, transform.position); // Jugador posición, Objeto posición (a, b) | (a-b)
var Angulo = Vector3.Angle (Jugador.position, transform.forward); // Angulo de rotación de un objeto.
DEBUG.
Debug.Log (Mensaje/Variable); // Imprime mensajes en la consola de Unity.
Debug.LogError (Mensaje/Variable); // Una variante del "Log" que imprime mensajes de error en la consola.
Debug.LogWarning (Mensaje/Variable); // variante del "Log", imprime mensajes de advertencia en la consola.
Debug.break; // Crea una pausa en el Editor, para poder checar scripting.
Debug.DrawLine (Start:Vector3, End:Vector3, color:Color); // Dibuja una línea inicio-final-color .
Debug.DrawRay (Start:Vector3, Dir:Vector3, color:Color); // Dibuja una línea inicio-Dir-color.
12
www.3dboxweb.com
PHYSICS.
var Distancia : float; var RayHit: RaycastHit; var Destino: Transform; var Radio : int;
OverlapSphere (transform.position, Radio) : Collider[] // Regresa un arreglo de colliders que tocan una esfera
Physics.Raycast (transform.position, transform.forward, RayHit, Distancia); // Línea con Distancia (Inicio, Dirección, info del Hit, Distancia).
Physics.Lineast (transform.position, Destino.position, RayHit); // Línea detecta colisiones (Inicio, Final, info del Hit).
Physics.IgnoreCollision (Instacia.collider, transform.root.collider, true); // Ignorar la colisión de la instancia con el personaje.
SCREEN.
Screen.showCursor = true / false; //Mostrar u Ocultar Mouse.
Screen.lockCursor = true / false; //Bloquear, Ocultar y Centrar el Mouse.
Screen.width; // Muestra la resolución en ancho en px.
Screen.height; // Muestra la resolución en alto en px.
Screen.fullScreen = true / false; // Cambia a pantalla completa.
Screen.SetResolution = (800, 600, true); // Asigna la resolución asignada.
APPLICATIONS.
Application.Quit; // Sale de la aplicación (Tecla Escape).
Application.CancelQuit; // Cancela el salir de la aplicación (Escape).
Application.LoadLeve ("NombreNivel"); // Carga 1 escena, debe de estar cargada en Build.
Application.CaptureScreenshot ("Screenshot.png"); // Captura una imagen en la ruta de la aplicación.
Application.OpenURL ("http://www.url.com"); // Cargar una liga para una dirección web.
AUDIO.
audio.Play (); // Reproducir audio.
audio.Stop (); // Detener audio.
audio.Pause (); // Pausa del audio.
audio.volume = 0.5; // Nivel del audio.
audio.mute = true/false; // Silenciar el audio.
audio.loop = true/false; // Loop del audio.
audio.PlayOneShot (Sonido); // Reproducir AudioClip.
yield WaitForSeconds (audio.clip.length); // Esperar a que termine el audio.
13
www.3dboxweb.com
GIZMOS ICON
function OnDrawGizmos (){
Gizmos.DrawIcon (transform.position, "WayPoint.psd"); // Debde estar dentro de una Carpeta “Gizmos”.
}
COMUNICACIÓN ENTRE SCRIPTS POR MEDIO DE VARIABLES DE TIPO SCRIPT. AI_Script1
var OtroScript : AI_Script2; // Variable para guardar la conexión con el otro Script (se tiene que llamar como el script a llamar).
OtroScript.NombreFuncion(); //Ejecutamos la función que hay en el “Script 2”, o se puede poner algún valor en variables.
OtroScript.Variable = 2; // Mandarle un nuevo valor a la variable del “Script 2”. AI_Script2 var Variable = 1; // Se deja en “Static” para poder acceder a la variable desde otro script. function NombreFuncion () {} // Se deja en “Static” para poder acceder a la función desde otro script.
COMUNICACIÓN ENTRE SCRIPTS POR MEDIO DEL GETCOMPONENT. Script_1 var A : int = 5; //Local en el mismo GameObject entrar a cualquier componente.
Script_2 = this.GetComponent ("Script_2"); //Target entrar al componente de otro GameObject en la escena.
Script_2 = GameObject.Find ("Sphere2").GetComponent ("Script_2"); print (A+Script_2.B); Script2.Ejecutar();
ENUM VARIABLES – LISTA: INSPECTOR.
enum vAcciOpciones { // CREAR VARIABLE CON OPCIONES DE SELECCINO DE LISTA
Atacar, Saltar, Correr, Esconder
}
var Acciones : vAcciOpciones; // Mostrar variable con opciones en el Inspector
if (Acciones == vAcciOpciones.Atacar) {} // si se selecciono Atacar crear una acción.
if (Acciones == vAcciOpciones.Saltar) {} // si se selecciono Saltar crear una acción.
if (Acciones == vAcciOpciones.Correr) {} // si se selecciono Correr crear una acción.
if (Acciones == vAcciOpciones.Esconder) {} // si se selecciono Esconder crear una acción.
Script_2
var B : int = 5;
function Ejecutar(){ //hacer algo }
14
www.3dboxweb.com
MATERIALES.
renderer.material.color = color.red; (green, blue, White. Black, yellow, cyan, magenta). // Cambio de Color en materiales.
renderer.material = VariableMaterial; // Aplicar un material.
renderer.material.mainTexture = VariableTextura; // Aplicar una Textura al color principal del material.
renderer.material.SetColor ("_SpecColor", Color.red); // Tipos de color: _Color, _SpecColor, _Emission, _ReflectColor.
renderer.material.SetTexture ("_MainText", VariableTextura); // Tipos de materiales: _MainText, _BumpMap, _Cube
BLENDING DE 2 MATERIALES (misma textura, solo diferentes atributos).
// Controla el Blending entre materiales que tengan las mismas texturas (solo cambien características).
var Material1 : Material;
var Material2 : Material;
var duration : int = 2.0;
function Update (){
// pingpong va de 0 a 1 y regresa, para controlar la velocidad se divide para regresar valor 1.
var Blend : float = Mathf.PingPong (Time.time, duration) / duration;
renderer.material.Lerp (Material1, Material2, Blend);
}
ANIMACION PARA MOVER TEXTURAS.
var Velocidad : float = 0.5;
function Update () {
var offset : float = Time.time * Velocidad;
// Cambiar el Offset del Diffuse en "X" progresivamente sin pasar del 1(%1).
renderer.material.SetTextureOffset ("_MainTex", Vector2(offset%1,0));
// Cambiar el Offset del Bump en "X" progresivamente sin pasar del 1
renderer.material.SetTextureOffset ("_BumpMap", Vector2(-offset%1,0));
}
15
www.3dboxweb.com
RAYCASTING.
DETECTAR COLLISION
// Si detecta que se acerca a 1.5 unidad en dirección hacia arriba
var Distancia : float =1.5;
if (Physics.Raycast (transform.position, Vector3.forward, Distancia) ){} //Lanza un Rayo (Posición, Dirección, Distancia).
Debug.DrawRay (transform.position, Vector3.forward*Distancia, Color.red); // Dibujar en Debug Líneas (Inicio, Dirección, Color).
LANZAR RAYO CON DISTASNCIA A DONDE APUNTE EL MOUSE (CAMARA).
var Distancia : int =10; // Distancia del Rayo
var rayo : RaycastHit; // Variable de Rayo
var rayo = Camera.main.ScreenPointToRay (Input.mousePosition); // rayo de la posición del mouse (Camara).
// Lanza un rayo y si golpea con algo regresara true
Physics.Raycast (Camera.main.transform.position, rayo.direction, hit, Distancia); // (Inicio, Dirección, info del Hit, Distancia).
Debug.DrawRay (Camera.main.transform.position, rayo.direction* Distancia, Color.red); // Dibujar en el editor el rayo con la misma info.
rayo.point: origen del rayo donde golpeo.
rayo.normal: en la cara de la normal en la que pego el rayo.
rayo.distance: distancia del rayo del punto de origen al destino.
rayo.collider: Obtener con que collider golpeo.
rayo.rigidbody: Obtener el Rigidbody del collider que golpeo.
rayo.transform: Obtener el transform del Rigidbody/collider con el que golpeo.
16
www.3dboxweb.com
TRIGGERS:
ACTIVAR: CON TRIGGERS ESPECÍFICOS (NOMBRE).
var V_Trigger : boolean;
function OnTriggerEnter (El_trigger : Collider){
if (El_trigger.gameObject.name == "Puerta"){
Debug.Log ("A entrado al área de ataque");
var V_Trigger : boolean = true;
}
}
DESACTIVAR: CON TRIGGERS ESPECÍFICOS (NOMBRE).
var V_Trigger : boolean;
function OnTriggerExit (El_trigger : Collider){
if (El_trigger.gameObject.name == "Puerta"){
Debug.Log ("A salido del área de ataque");
var V_Trigger : boolean = false;
}
}
ACTIVADO: CON TRIGGERS ESPECÍFICOS (NOMBRE).
var V_Trigger : boolean;
function OnTriggerStay (El_trigger : Collider){
if (El_trigger.gameObject.name == "Puerta"){
Debug.Log ("Sigue sobre el área de ataque");
}
}
17
www.3dboxweb.com
COLLISIONS:
COLISION CON COLLIDERS EN ESPECÍFICO
function OnCollisionEnter (Colisionando : Collision){
if (Colisionando.gameObject.name == "NombreMesh"){
Debug.Log ("Colisión con el mesh: NombreMesh");
}
}
COLISION SOBRE CUALQUIER COLLIDER Y SABER POSICION Y CARA NORMAL.
var ParticleExplotion : GameObject;
function OnCollisionEnter (Colisionando : Collision){
//variable "contactPoint" para saber x, y, z de del objeto al colisionar.
var Impacto : ContactPoint = Colisionando.contacts[0];
Debug.Log ("Posicion: " + Impacto.point);
Debug.Log ("Normal: " + Impacto.normal);
Debug.Log ("Nombre: " + Impacto.otherCollider.name);
Debug.Log ("Prefab: " + Impacto.thisCollider.name);
//Sobre la cara que impacto el misil obtener la cara de la normal de frente (up) .
var rotacion = Quaternion.FromToRotation ( Vector3.up, Impacto.normal );
//crear la instancia dinámica de la explosión con la posición y la cara de enfrente donde colisiono y aplicar partículas de
explosión.
var InstantiateExplosion : GameObject = Instantiate( ParticleExplotion, impacto.point, rotacion);
}
18
www.3dboxweb.com
DYNAMICS.
MOVER RIGIDBODIES.
gameObject.name.AddComponent (Rigidbody); //Agregar componente de Rigidbody.
rigidbody.AddForce (Vector3 (0, 10, 0)); //Agregar una fuerza a un Rigidbody.
rigidbody.velocity = transform.TransformDirection (0, 0, speed); //Mover objeto con Rigidbody.
LANZAR INSTANCIA RIGIDBODY SIN COLISIONAR CON EL PLAYER.
var Bala : Rigidbody;
var speed = 30;
//crear instancias a partir de la variable dinámica para cargar objetos de tipo Rigidbody (misil).
var Bala_Instanseada : Rigidbody = Instantiate(Bala, transform.position, transform.rotation);
//Que el misil cuando se cree dinámicamente (instanseado) no colisione con el personaje (root).
Physics.IgnoreCollision (Bala_Instanseada.collider, transform.root.collider, true);
//LocalSpace a WorlSpace, Como el objeto es Rigidbody, este tiene propiedades de velocidad, y le agregamos una fuerza inicial por la variable dinámica
Bala_Instanseada.velocity = transform.TransformDirection (0, 0, speed);
CREAR EXPLOSION RIGIDBIDY.
var explosionRadius = 5;
var explosionPower = 2000.0;
//Cuando el misil se impacta busca en un radio quienes tienen "colliders" y los almacena en un arreglo.
var colliders : Collider[] = Physics.OverlapSphere( transform.position, explosionRadius );
//Descargamos todos los colliders almacenados en el arreglo en una variable "hit".
for (var hit in colliders){
// Para que NO intente mover cualquier objeto con "collider" si el collider tiene Rigidbody le agregamos una fuerza para poderlo impulsarlo.
if (hit.rigidbody){
//agregar impulso al objeto "rigidbody" que este en el mismo radio cuando impacto el misil.
hit.rigidbody.AddExplosionForce (explosionPower, transform.position, explosionRadius);
}
}
19
www.3dboxweb.com
RAGDOLL.
//Variable para cargar el RagDoll
var Ragdoll_Body : Transform;
function Start (){
//Reproducción de animación
animation.wrapMode = WrapMode.Loop;
animation.Play ("run");
// Esperar
yield WaitForSeconds (1.5);
//Destruir Mesh animado
Destroy(gameObject);
// Instancia para cambiar por ragdoll
var Morir : Transform = Instantiate(Ragdoll_Body, transform.position, transform.rotation);
Switch_Ragdoll (transform, Morir);
}
function Switch_Ragdoll (Fuente : Transform, Destino : Transform) {
Destino.position = Fuente.position;
Destino.rotation = Fuente.rotation;
// Igualar los valores de "transform" que tienen el mismo nombre.
for (var child : Transform in Destino) {
var JointTransforms = Fuente.Find(child.name);
Switch_Ragdoll (JointTransforms, child);
}
}
20
www.3dboxweb.com
SCREEN POINT RAY (CLICK & MOVE/ROTATE).
// Genera un Rayo desde la posición del puntero del mouse.
var rayo : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
// Variable para saber cuándo se crea un rayo y pega con algo.
var hit : RaycastHit;
//MOVER
//hasta que se le de click en una posición nos dé la posición.
if (Physics.Raycast (rayo, hit)){
//Obtener del RayCast el punto donde se lanzo el rayo (x, y, z) ' Vector3.
PosicionDestino = hit.point;
//ROTAR
if (PlanoEscena.Raycast (rayo, hitDist)) {
//Obtener la Posición donde se dio click del Plano.
var ClickPosicion = rayo.GetPoint(hitDist);
//De acuerdo a la posición calcular el ángulo de rotación.
var RotacionPlayer= Quaternion.LookRotation(ClickPosicion - transform.position);
// Rotar el objeto con los ángulos de Rot. Obtenidos.
transform.rotation = RotacionPlayer;
}
//Mover constantemente al personaje a la nueva PosicionDestino.
transform.position = Vector3.Lerp (transform.position, PosicionDestino, Time.deltaTime * Mover);
}
21
www.3dboxweb.com
SAVE & LOAD SCENE VALUES:
AI_CheckPoint var vCheckPoint : String; var Script_Salvar : AI_Save_Load;
function OnTriggerEnter () { Script_Salvar.Salvar_CP = vCheckPoint; print ("Checkpoint >" +vCheckPoint+ "< Activado"); }
AI_Save_Load
var Salvar_CP : String = "A"; var Character : GameObject; function Update () { //SAVE - Click Izquierdo if (Input.GetButtonDown ("Salvar")) {
PlayerPrefs.SetString("info", Salvar_CP); print ("Salvado: "+Salvar_CP); } //LOAD - Click Derecho
if (Input.GetButtonDown ("Cargar")) { Application.LoadLevel ("Escena"); }
} // CREAR PERSONAJE DINAMICAMENTE function Start (){ //La información se guarda en: HKEY_CURRENT_USER/Software/<compañía>/<proyecto> var Save_Load : String = PlayerPrefs.GetString("info"); print ("Check Point Cargado: " + Save_Load);
if (Save_Load == "A"){ Instantiate (Character, Vector3 (0,0,0), transform.rotation);
} else if (Save_Load == "B"){ Instantiate (Character, Vector3 (0,0,11), transform.rotation); }
else if (Save_Load == "C"){ Instantiate (Character, Vector3 (0,0,24), transform.rotation); } else if (Save_Load == "D"){ Instantiate (Character, Vector3 (0,0,38), transform.rotation); } }
22
www.3dboxweb.com
ANIMATION:
ANIMATION STATES. //Reproducir la animación general o por animación. animation.Play(); / animation.Play("Subir");
//Detener la animación general y rebobinar o por animación. animation.Stop(); / animation.Stop("Subir"); //Detener la animación en general o por animación.
animation.Rewind(); / animation.Rewind("Subir");
//Activar/Desactivar (Pause) la animación en general o por animación. animation.enabled = true/false; / animation["walk"].enabled = true/false; //Controla la animación Walk su velocidad = reproducción atrás (-1)/Adelante (1). animation["walk"].speed = -1 ó 1; //Fade al cambiar a animación Walk Fade del Split Walk con los otros splits en 2 seg.
animation.CrossFade ("Walk"); / animation.CrossFade ("Walk", 0.2); //Esperar hasta que la animación termine de reproducir.
yield WaitForSeconds (animation.clip.lenght); //Modo de reproducción de las animaciones animation.wrapMode = WrapMode. Loop; (WrapMode.default, .One, .Loop, .PingPong, .ClampForever).
animation ["NomAnim"].wrapMode = WrapMode.Loop; // Modeo de reproducción de una animación. GET CHARACTER CONTROLLER. // Obtener los componentes de "CharacterController" y saber cuando el personaje toca el piso.
var controller : CharacterController = GetComponent(CharacterController); if (controller.isGrounded){ //Acción}
GET CHARACTER MOTOR. // Obtener los componentes de "CharacterMotor" y modificar velocidad de movimientos del player.
var Motor : CharacterMotor = GetComponent(CharacterMotor); Motor.movement.maxForwardSpeed = 1.0; Motor.movement.maxSidewaysSpeed = 1.0; Motor.movement.maxBackwardsSpeed = 1.0;
23
www.3dboxweb.com
GUI: TEXTURE / TEXT:
GUI BUTTON TEXTURES.
//variable de sonido
var Sonido : AudioClip;
//variables de nivel y texturas (cambiar).
var NivelCargar : String;
var Textura_A : Texture2D;
var Textura_B : Texture2D;
//Al poner el mouse encima cambiar a textura B
function OnMouseEnter () {
guiTexture.texture = Textura_B;
}
//Al salir el mouse cambiar a textura A
function OnMouseExit (){
guiTexture.texture = Textura_A;
}
//Al hacer click y soltar el botón del ratón cargar el nivel
function OnMouseUp (){
Application.LoadLevel (NivelCargar);
}
GUI BAR TEXTURE
// Cambio del Pixel Inset en Textures
guiTexture.pixelInset =
Rect (ValorXInset, ValorYInset, WithInset, HeightInset);
POSICION DE GUITEXTURE DE ACUERDO A RESOLUCIÓN
var position : Rect;
var vTexture : Texture2D;
function Start(){
position = Rect( ( Screen.width - vTexture.width ) / 2, (
Screen.heigh - vTexture.height ) / 2, vTexture.width,
vTexture.height );
}
function OnGUI(){
GUI.DrawTexture( position, crosshairTexture );
}
GUI TEXT.
// Texto
guiText.text = "Texto";
// Texto + Variable
guiText.text = "Texto" + Variable;
// Variable convertida a string
guiText.text = Variable.ToString();
// Cambio de color en el material del texto
guiText.material.color = Color.green;
// Cambio dinámico del tamaño del texto
guiText.fontSize = 12;
// Cambio dinámico del estilo del texto
guiTextfontStyle = FontStyle.Bold;
24
www.3dboxweb.com
. YIELD / CORRUTINAS:
1. Ejemplo ----- Sin corrutina (probar esto en Update No funciona sin corrutina).
// Se suspende por 2 segundos
yield WaitForSeconds (2); //Imprimir el valor del tiempo 5 seg.
Debug.Log (Time.time);
2. Ejemplo ----- Ejecuta a “Tiempo” pero continúa después de llamar “Tiempo” inmediatamente.
Tiempo ();
print ("Imprimir ahora");
function Tiempo () {
Debug.Log ("Imptimir al instante");
yield WaitForSeconds (2);
Debug.Log ("Imprimir 2 seg despues");
}
3. Ejemplo ----- Ejecutara “Tiempo” y esperar hasta que termine antes su propia ejecución.
// Iniciar la Corrutina y accionar Función Tiempo.
yield StartCoroutine ("Tiempo");
Debug.Log ("Imprimir después de 2 Seg de Función Tiempo");
function Tiempo () {
Debug.Log ("Tiempo --> Al instante");
yield WaitForSeconds (2);
Debug.Log ("Tiempo --> A los 2 Seg");
}
25
www.3dboxweb.com
INVOKE - CORRUTINAS:
1. Ejemplo ----- Ejecutar.
//invocar: (función, tiempo ejecución).
Invoke ("FuncionDeo", 2);
function FuncionDeo () {
Debug.Log ("Se activa al tiempo: " + Time.time + " Seg");
}
2. Ejemplo ----- Repetición
//invocar repetidamente: (función, tiempo ejecución, cada X segundos).
InvokeRepeating ("ElTiempo", 0, 1);
function ElTiempo () {
Debug.Log ("Se activa al tiempo: " + Time.time + " Seg");
}
3. Ejemplo ----- Repetición / Cancelar.
var Esfera : Rigidbody;
InvokeRepeating("LanzarEsfera", 0, 0.5); //Activar Invoke
function LanzarEsfera () {
Instantiate(Esfera).velocity = Vector3 (0, 0, Random.Range(1, 20));
}
// Cancelar la repetición cuando del invoke al presionar click.
function Update () {
if (Input.GetKeyDown (KeyCode.Mouse0)){
CancelInvoke (); //Cancelar Invoke.
}
}