Noticias

¡RECUERDA QUE SI ERES UN NUEVO USUARIO, DEBES PRESENTARTE PARA PODER PUBLICAR MENSAJES! | TENEMOS CANAL OFICIAL DE TELEGRAM: t.me/unity3dspain

Necesito ayuda con mi controladorPersonaje(Solucionado)

Iniciado por Bousing, Agosto 13, 2015, 07:12:10 PM

Tema anterior - Siguiente tema
Agosto 13, 2015, 07:12:10 PM Ultima modificación: Agosto 20, 2015, 12:10:56 AM por Bousing
Saludos a todos!!!Estoy empezando mi propio proyecto en Unity, un juego de tercera persona, tengo muchos problemas. Pues verán, soy programador y aunque no estoy muy familiarizado con el API de Unity me las he arreglado para crear mi propio Script para controlar el personaje (Se que hay muchos en internet pero si quiero aprender a programar videojuegos y tener mi propia firma debo hacer el código yo). Mi Script funciona al pelo, puedo mover mi personaje, saltar, girarlo (Esta ultima función tiene un desperfecto, mas adelante lo explico). En fin el script hace que el jugador mueva el personaje por el terreno bien... pero sucede lo siguiente:1) El colisionador del jugador no funciona, tiene el  CharacterController y no funciona bien, el jugador se hunde en el piso del terreno, atraviesa las montañas, atraviesas los objetos, y todo esta al pelo, el terreno tiene activado su collider, no esta en IsTrigger, no se porque pero pienso que es por las animaciones...Las animaciones no las hice yo, las descargue del Asset Store y son las animaciones de Raw Mocap Data y creo que atraviesa cualquier cosa  es por la animación, de hecho el jugador cuando se sale del terreno, se cae pero si el usuario teclea W o la flecha el sigue caminando en el aire porque esta programado para que el ejecute esa animación cuando se ejecuta el Input.GetAxis("Vertical"), intente solucionarlo con el booleano IsGrounded que esta en la clase de CharacterController pero el jugador no se me mueve.2) Como bien dije antes tengo un desperfecto con el giro del personaje, el gira bien si el usuario toca varias veces A o D o las flechitas, pero quiero que gire mientras el usuario mantenga presionado esos botones, no que los haga varias veces, como hago eso ?     Bueno compartiré mi script con ustedes para saber si es que hay algún error y adjuntare un screen  para que vean lo que sucede con mi jugador en el terreno. Otra cosa mi personaje fue hecho con MakeHuman, me gusta mucho esa herramienta.using UnityEngine;
using System.Collections;
public class ControladorPersona : MonoBehaviour {    // Use this for initialization
    private Animator animator;
    public float speed = 100;
    public float rotacion = 100;
    public float JumpForce = 2;
    private bool IsGrounded;
    //private bool AfterJump = false;   
    private CharacterController controller;
        void Start () {
        animator = GetComponent<Animator> (); //SE INICIALIZA EL ANIMATOR EN animator
        controller = GetComponent<CharacterController> (); //SE INICIALIZA EL CharacterController
    }
    
    // Update is called once per frame
    void Update(){        //CONDICION PARA MOVER EL JUGADOR HACIA ADELANTE
        if (Input.GetAxis ("Vertical") > 0.2) {
            Correr ();
        }
        else {
            Idle ();  
             }        //CONDICION PARA HACER QUE EL JUGADOR SALTE
        if (Input.GetButtonDown ("Jump")) {
            Jump();
            AfterJump = true;
        }        //CONDICION PARA QUE EL JUGADOR SE QUEDE EN REPOSO (Idle) POR DEFECTO
        if (Input.GetAxis ("Vertical") == 0) {
            Idle();
        }        //CONDICION PARA QUE EL PERSONAJE ROTE
        if (Input.GetButtonDown ("Horizontal")) {
            float h = Input.GetAxis("Horizontal");
            transform.Rotate(0,h * rotacion * Time.deltaTime,0);
        }
        //CONDICION PARA QUE EL JUGADOR CAMINE HACIA ATRAS
        if (Input.GetAxis ("Vertical") < 0) {
            ParaAtras();
        }
    }
            //FUNCION PARA HACER QUE EL PERSONAJE CORRA
    void Correr(){
        animator.SetBool ("Atras", false); //EL JUGADOR SE MUEVE HACIA ADELANTE
        float v = Input.GetAxis("Vertical");
        animator.SetFloat ("Speed", speed); //CAMBIA DE ESTADO A CORRER
        //animator.SetBool ("IsGrounded", true); //EL PERSONAJE TOCA EL SUELO
        transform.Translate (0, 0, v * speed * Time.deltaTime); //MOVER EL PERSONAJE HACIA ADELANTE    }    //FUNCION PARA HACER QUE EL PERSONAJE ESTE EN RESPOSO (Idle)
    void Idle(){
        animator.SetBool ("IsGrounded", true);
        animator.SetFloat ("Speed", 0); //EL JUGADOR NO CAMINA/CORRE
        /*
        if (AfterJump == true) {
        animator.SetBool ("IsGrounded", true);
            AfterJump = false;
        }*/
    }    //FUNCION PARA HACER QUE EL PERSONAJE SALTE
    void Jump(){
        animator.SetBool ("IsGrounded", false); //EL JUGADOR YA NO PISA EL SUELO
        rigidbody.AddForce (JumpForce, 0, 0);
    
    }    void ParaAtras(){
        animator.SetBool ("Atras", true); //EL JUGADOR CAMBIA DE ESTADO Y CAMINARA HACIA ATRAS
        float v = Input.GetAxis("Vertical");
        v = v * -1; 
        transform.Translate (0, 0, v * speed * Time.deltaTime);
    }
}   Espero que les haya gustado mi Script, lo hice de manera estructurada y si alguien sabe como solucionar mis problemas estaré muy agradecido si puede decirmelo. Saludos a todos y muchas gracias por su tiempo.    

El charactercontroller tiene un collider? Compruébalo que no lo se. Prueba de poner inicialmente al jugador muy arriba en y, no sea que el collider interseccione con el terreno.

sí, y si no me equivoco el CharacterController es un collider, de hecho esta en la sección de componentes físicos. El trae un colisionador como el de la capusula , yo pongo el jugador muy arriba, el se cae por la gravedad, pero se atraviesa un poco el terreno y se queda ahí como en la imagen que ajunte anteriormente.Aqui una imagen del jugador con su CharacterController   





Vale. Desactiva el terreno y pon un plano con un collider. Tambien lo atraviesa cuando cae el personaje desde arriba?

reduce el colider, a mi me pasa lo mismo, no se si es un problema de unity 5 o que, si... las animaciones hacen que no vaya mejor...las tendras que retocar casi todas quiero que gire mientras el usuario mantenga presionado esos botones, no que los haga varias veces, como hago eso ?  con la animacion de turn que gira en corto las tienes en el mismo aset

No funciono, es extraño, no logro solucionar el problema. Estoy utilizando el Unity4 porque me advirtieron que el 5 tiene ese problema...

Sube la escena y lo miramos, aunque yo tengo el 5.


Pero tienes que exportarlo todo, no solamente la escena sin objetos. B.Derecho sobre Assets -> Export Package

Aumenta el skin . width, ha de mantener la proporción.
Enviado desde mi SM-N910F mediante Tapatalk

Ya solucione el problema, aunque no tiene sentido era que el CharacterController debía estar por debajo del personaje y no dentro de él como lo mostré antes, esto lo descubrí porque quize meterle el script controlador de tercera persona que Unity trae y por defecto eso lo configura así y ya no se hunde en el suelo. Atraviesa las montañas y los objetos pero es culpa del script que programe (deje el código al principio). No se como hacer para que el personaje si no detecta el suelo se caiga y bloquee la animación, ya que con mi Script puedo correr en el aíre, cosa que no debe suceder. Yo tengo un Script muy bueno y funciona al pelo, pero como dije antes todo el código del proyecto lo quiero hacer yo por mi cuenta, así que no lo quiero usar en mi juego. Intente estudiar el código de ese script pero esta programado de una manera muy diferente al mio y como no estoy familiarizado con el API de Unity no lo entiendo lo compartiré a continuación para que me ayuden a descubrir como ese programador hizo para hacer que el muñeco no atraviese los objetos y cuando este caminando en el aire se caiga y no siga caminando.Acoto algo antes, ya he probado con el booleano IsGrounded, lo pongo como condición dentro de todos mis IF pero no me funciona  using UnityEngine;
using System.Collections;// Require these components when using this script
[RequireComponent(typeof (Animator))]
[RequireComponent(typeof (CapsuleCollider))]
[RequireComponent(typeof (Rigidbody))]
public class BotControlScript : MonoBehaviour
{
    public Transform enemy;    [System.NonSerialized]                    
    public float lookWeight;                    // the amount to transition when using head look
    
    //[System.NonSerialized]
    //public Transform enemy;                        // a transform to Lerp the camera to during head look
    
    public float animSpeed = 1.5f;                // a public setting for overall animator animation speed
    public float lookSmoother = 3f;                // a smoothing setting for camera motion
    public bool useCurves;                        // a setting for teaching purposes to show use of curves    
    private Animator anim;                            // a reference to the animator on the character
    private AnimatorStateInfo currentBaseState;            // a reference to the current state of the animator, used for base layer
    private AnimatorStateInfo layer2CurrentState;    // a reference to the current state of the animator, used for layer 2
    private CapsuleCollider col;                    // a reference to the capsule collider of the character
        static int idleState = Animator.StringToHash("Base Layer.Idle");    
    static int locoState = Animator.StringToHash("Base Layer.Locomotion");            // these integers are references to our animator's states
    static int jumpState = Animator.StringToHash("Base Layer.Jump");                // and are used to check state for various actions to occur
    static int jumpDownState = Animator.StringToHash("Base Layer.JumpDown");        // within our FixedUpdate() function below
    static int fallState = Animator.StringToHash("Base Layer.Fall");
    static int rollState = Animator.StringToHash("Base Layer.Roll");
    static int waveState = Animator.StringToHash("Layer2.Wave");
        void Start ()
    {
        // initialising reference variables
        anim = GetComponent<Animator>();                      
        col = GetComponent<CapsuleCollider>();                
//        enemy = GameObject.Find("Enemy").transform;    
        if(anim.layerCount ==2)
            anim.SetLayerWeight(1, 1);
    }
    
    
    void FixedUpdate ()
    {
        float h = Input.GetAxis("Horizontal");                // setup h variable as our horizontal input axis
        float v = Input.GetAxis("Vertical");                // setup v variables as our vertical input axis
        anim.SetFloat("Speed", v);                            // set our animator's float parameter 'Speed' equal to the vertical input axis                
        anim.SetFloat("Direction", h);                         // set our animator's float parameter 'Direction' equal to the horizontal input axis        
        anim.speed = animSpeed;                                // set the speed of our animator to the public variable 'animSpeed'
        anim.SetLookAtWeight(lookWeight);                    // set the Look At Weight - amount to use look at IK vs using the head's animation
        currentBaseState = anim.GetCurrentAnimatorStateInfo(0);    // set our currentState variable to the current state of the Base Layer (0) of animation
        
        if(anim.layerCount ==2)        
            layer2CurrentState = anim.GetCurrentAnimatorStateInfo(1);    // set our layer2CurrentState variable to the current state of the second Layer (1) of animation
        
        
        // LOOK AT ENEMY
        
        // if we hold Alt..
        if(Input.GetButton("Fire2"))
        {
            // ...set a position to look at with the head, and use Lerp to smooth the look weight from animation to IK (see line 54)
            anim.SetLookAtPosition(enemy.position);
            lookWeight = Mathf.Lerp(lookWeight,1f,Time.deltaTime*lookSmoother);
        }
        // else, return to using animation for the head by lerping back to 0 for look at weight
        else
        {
            lookWeight = Mathf.Lerp(lookWeight,0f,Time.deltaTime*lookSmoother);
        }
        
        // STANDARD JUMPING
        
        // if we are currently in a state called Locomotion (see line 25), then allow Jump input (Space) to set the Jump bool parameter in the Animator to true
        if (currentBaseState.nameHash == locoState)
        {
            if(Input.GetButtonDown("Jump"))
            {
                anim.SetBool("Jump", true);
            }
        }
        
        // if we are in the jumping state... 
        else if(currentBaseState.nameHash == jumpState)
        {
            //  ..and not still in transition..
            if(!anim.IsInTransition(0))
            {
                if(useCurves)
                    // ..set the collider height to a float curve in the clip called ColliderHeight
                    col.height = anim.GetFloat("ColliderHeight");
                
                // reset the Jump bool so we can jump again, and so that the state does not loop 
                anim.SetBool("Jump", false);
            }
            
            // Raycast down from the center of the character.. 
            Ray ray = new Ray(transform.position + Vector3.up, -Vector3.up);
            RaycastHit hitInfo = new RaycastHit();
            
            if (Physics.Raycast(ray, out hitInfo))
            {
                // ..if distance to the ground is more than 1.75, use Match Target
                if (hitInfo.distance > 1.75f)
                {
                    
                    // MatchTarget allows us to take over animation and smoothly transition our character towards a location - the hit point from the ray.
                    // Here we're telling the Root of the character to only be influenced on the Y axis (MatchTargetWeightMask) and only occur between 0.35 and 0.5
                    // of the timeline of our animation clip
                    anim.MatchTarget(hitInfo.point, Quaternion.identity, AvatarTarget.Root, new MatchTargetWeightMask(new Vector3(0, 1, 0), 0), 0.35f, 0.5f);
                }
            }
        }
        
        
        // JUMP DOWN AND ROLL 
        
        // if we are jumping down, set our Collider's Y position to the float curve from the animation clip - 
        // this is a slight lowering so that the collider hits the floor as the character extends his legs
        else if (currentBaseState.nameHash == jumpDownState)
        {
            col.center = new Vector3(0, anim.GetFloat("ColliderY"), 0);
        }
        
        // if we are falling, set our Grounded boolean to true when our character's root 
        // position is less that 0.6, this allows us to transition from fall into roll and run
        // we then set the Collider's Height equal to the float curve from the animation clip
        else if (currentBaseState.nameHash == fallState)
        {
            col.height = anim.GetFloat("ColliderHeight");
        }
        
        // if we are in the roll state and not in transition, set Collider Height to the float curve from the animation clip 
        // this ensures we are in a short spherical capsule height during the roll, so we can smash through the lower
        // boxes, and then extends the collider as we come out of the roll
        // we also moderate the Y position of the collider using another of these curves on line 128
        else if (currentBaseState.nameHash == rollState)
        {
            if(!anim.IsInTransition(0))
            {
                if(useCurves)
                    col.height = anim.GetFloat("ColliderHeight");
                
                col.center = new Vector3(0, anim.GetFloat("ColliderY"), 0);
                
            }
        }
        // IDLE
        
        // check if we are at idle, if so, let us Wave!
        else if (currentBaseState.nameHash == idleState)
        {
            if(Input.GetButtonUp("Jump"))
            {
                anim.SetBool("Wave", true);
            }
        }
        // if we enter the waving state, reset the bool to let us wave again in future
        if(layer2CurrentState.nameHash == waveState)
        {
            anim.SetBool("Wave", false);
        }
    }
}Espero que puedan ayudarme y muchísimas gracias a los que han respondido en este post, saludos.

Etiquetas: