Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Mensajes - ramunda

#31
Cita de: iRobb date=1488624434Estás aplicando una force dependiente de la mass del body. Qué mass tienes puesta? Piensa en hacerla independiente de la mass cambiando el ForceMode a acceleration o velocity p.ej o cambiándolo a una mass real si es un coche ( 1 = 1kg por convenio, 1500 de unidad p.ej.)
   
   
      Desconozco los valores de girar/marcha, y probablemente serán demasiado grandes.
   
   
      Ponlo en el fixedUpdate ya que es physics.
   
   
      Error no va a dar ya que sintácticamente es correcto. Al final es un equilibrio entre todos los valores y a una situación concreta. Tendrás que irlo afinando.
   


Gracias iRobb , la masa la tengo al 1, si la subio no se mueve , los valores marxa y velocidad de giro estan en 50/100 los dos.
 
lo he puesto en FixedUpdate ahora si acelera correctamente lo he dejado asi:
 

using System.Collections;
using UnityEngine;
    public class controlbarco : MonoBehaviour {

public float velocidadgiro = 50f;
public float marcha=50f;
public float marxamax = 60f;
float startY;
private Rigidbody rb;
public GameObject espuma;
float espumas = 0f;
void Start()
{
   rb = GetComponent<Rigidbody>();
   espuma.SetActive (false);
   
}
void FixedUpdate () {
   
   float h = Input.GetAxis ("Horizontal") * velocidadgiro;
   float v = Input.GetAxis ("gatilloderecha") * marcha * Time.deltaTime;
   rb.AddTorque(transform.up *h);
   rb.velocity = transform.forward * v;
   
}
}

 
Muchas gracias por todo, un saludo cordial.
 
 
#32
Buenos dias comunidad.
 
Agradecería si podéis decirme donde estoy fallando y porque...
 
He creado estas 4 lineas de codigo , nada del otro mundo, para mover un objeto adelante y hacia los lados etc con los axis verticales y horizontales,.
 
 
 

using System.Collections;
using UnityEngine;
    public class controlbarco : MonoBehaviour {

public float velocidadgiro=0f;
public float marcha=0f;
float startY;
private Rigidbody rb;
void Start()
{
   rb = GetComponent<Rigidbody>();

}
void Update () {
   
float girar =Input.GetAxis("Horizontal");
float adelante =Input.GetAxis("gatilloderecha");
   
rb.AddTorque(transform.up*velocidadgiro*girar*Time.deltatime);
rb.AddForce(transform.forward*adelante*marcha*Time.deltatime);
   
    }
    }

 
bien, la idea era que girara / acelerara a una velocidad paulatina osea con el Time.deltatime hasta alcanzar el valor de el float correspondiente.
 
Pues no. no se mueve en absoluto , en cambio si le quito los Time.....si se mueve pero alcanza la velocidad tanto de giro como de marcha de golpe  y sigue acelerando sin parar! de acelerar asi;:
 

rb.AddTorque(transform.up*velocidadgiro*girar);
rb.AddForce(transform.forward*adelante*marcha);

 
Y la pregunta es:
 
Que estoy haciendo mal :)
 
No da error..
 
Gracias de antemano!!!
 
 
#33
Madre mía...como no lo he visto...:( oxidado no..estoy para desguace hahha.
 
No estoy delante de el pc para confirmarte que funciona, pero estoy al 100% seguro y de acuerdo con que es eso.
 
Mil gracias por la atención y la pronteza.
 
Un abrazo!!
 
P.D esta noche confirmo y doy el post como resuelto :).
 
Edito: todo resuelto , funciona de maravilla.
 
Gracias!!!
 
 
#34
Cita de: lightbug date=1487772229Hola! no me quedo claro si te imprime el "tocado", osea si funciona el triggerenter.
   


Hola lightbud , gracias por el interés, la respuesta es SI, imprime el "tocado" , lo puse  adrede para ver si se realizaba la colisión :)
#35
Muy buenas tardes, he retomado Unity después de un letargo....y creo que me he oxidado...
 
Según lo que sabia esto deberia funcionar, pero por al guna razón se me olvida algo que no se que es.
 
Tengo dos GO(Gameobjects), uno con rigid t triger y collider y el otro con collider sin triguer.
 
En uno tengo este script:
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class tiempodinero : MonoBehaviour {
public static float totaldinero = 400f;
public Text dinero;
void Start () {
dinero.text=string.Format ("{0}","$"+totaldinero);
}
}

 
bien funciona perfectamente y se muestra en pantalla el valor de 400.
 
Ahora en el otro objeto tengo que restarle 50 al valor de 400 al entrar en contacto(triggerenter) y lo pongo asi:
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class restadinero : MonoBehaviour {
void OnTriggerEnter(Collider other)
{
   if (other.tag == "gas")
   {
      Debug.Log("tocado");
      tiempodinero.totaldinero -= 50f;
   
   }
}
}

 
Bien esto deberia restar 50 al 400....unity no me da error ni nada, pero, no me resta el valor.
 
Ni que decir tiene que los tags están al dia.
 
Agradecería una pequeña ayuda/sugerencia.
 
Gracias de antemano.
 
 
 
 
 
 
 
 
 
 
#36
General (Antiguo) / Configurable Joint...
Febrero 18, 2017, 01:20:40 AM
Cita de: lightbug date=1487377032Ah no sabia eso, a lo que me referia con guardar las propiedades: si cuando creas un Joint de esos vos tocas por ej 2 de las propiedades, cruciales para tu caso P1 y P2. Entonces guardas esas propiedades en tu script. Luego cuando te reenganchas pones el addcomponent y despues getcomponent<ConfigurableJoint>().Prop1 = P1 , y lo mismo con P2.
   
   
      Ojo no se si hay una mejor manera de hacerlo, fijandome por ahi la mayoria los destruyen.
   
   
      Intentare lo que me comentas compañero, de antemano, Gracias , cuando tenga la cosa arreglada lo posyeare para futuras dudas!!, mil gracias.
   


 
#37
General (Antiguo) / Configurable Joint...
Febrero 18, 2017, 01:04:19 AM
Cita de: lightbug date=1487376065Hola ramunda, podes pensarlo asi, en tener las propiedades de dicho Joint guardadas, entonces cuando lo queres agregas el componente y le pones dichas propiedades, cuando no lo queres le aplicas un Destroy y listo.
   


Gracias lightbug , el tema del Destroy lo tenia presente , pero lo de que se pudieran guardar las propiedades.....no tengo ni idea de como hacerlo.
 
He intentado esto:
 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class joint : MonoBehaviour {
public GameObject trailer;
   
// Use this for initialization
void Start () {
   trailer.GetComponent<ConfigurableJoint> ().xMotion = ConfigurableJointMotion.Free;
   trailer.GetComponent<ConfigurableJoint> ().yMotion = ConfigurableJointMotion.Free;
   trailer.GetComponent<ConfigurableJoint> ().zMotion = ConfigurableJointMotion.Free;
}

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

 
Funciona como script aparte lo que hace es cambiar los valores x,y,z y lo deja en free loq eu hace es desenganchar el remolque , lo malo es cuando reactivo el script reponiendo las x,y,z en locked...es un completo desastre...
 
 
#38
General (Antiguo) / Configurable Joint...
Febrero 18, 2017, 12:42:42 AM
Buenas noches a todos, agradecería una ayuda o sugerencia de como desactivar un Configurable Joint...
 
Como bien sabemos(i si no lo saben aquí lo expongo), el dichoso no lleva el tipico cuadradito de desactivame.
 
Bien la cosa es que el Enabled o el Setactive tampoco lo desactivan....
 
Y direis para que lo quiero desactivar, bien , pues sencillo , tengo un camion de carga que al acercarse al trailer se engancha a el ,y asi es pero no hay quien lo despegue de allí , la manera correcta seria desactivando dicho...Joint.
 
 
 
Agradecería una luz.
 
Muchas gracias de antemano.
 
P.D el Configurable joint esta en el remolque y lleva el body de el camión que lo arrastra.
 
 
#39
General (Antiguo) / contoles xbox 360
Septiembre 23, 2016, 11:35:01 PM
Gracias a todos, de momento he conseguido algún avance mapeando el Horizontal y el Vertical de el script con los axis de el mando y algo he conseguido...no es exactamente...manejablee pero voy por el camino .
 
Gracias iRoob.( y si si veo que no avanzo con esto lo subo en un drive).
 
Gracias Kaito.(si estuve mirando pero no saque nada claro).
 
 
 
 
#40
General (Antiguo) / contoles xbox 360
Septiembre 23, 2016, 03:32:47 PM
Cita de: pioj date=1474637426Ref. Primeros Pasos: Código muy largo y pesado de leer...
   
   
      No uso el CrossPlatform porque es un follón de asset, y está enredado. Te recomiendo cambiar de método a : InControl

       
   


Gracias pioj tengo el InControl, es el que me ha mapeado todos los controles en el input manager pero no consigo hacerlo rular.
 
Volvere a comerme el tutorial de nuevo aver si tengo suerte , gracias.
 
 
#41
General (Antiguo) / contoles xbox 360
Septiembre 23, 2016, 02:46:02 PM
Buenas tardes, me estoy volviendo loco para poder usar el controlador de Xbox 360 con el movimiento de este caballo....
 
el Script esta para que se mueva con las teclas w,s.a.d o con las arrow, pero quiero mapearlo a el controlador de xbox....
 
Ya tengo puestos en el input todos los posibles axis, botones etc...
 
Pero ahora me encientro que no veo la manera de aplicarlos para que se mueva con ellos....
 
 
 
Agradecería una ayuda por favor.
 
Adjunto todo el script aunque no creo que aga falta pero para facilitar ;
 
 
 

using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;
 
[RequireComponent(typeof(HashIDs))]
public class HorseController : MonoBehaviour
{
    public enum HorseMeshType
    {
        Horse1 = , Horse2 = 1, BigHorse = 2, PolyArt = 3, MineCraft = 4, Custom = 5
    }
    //float normalizedtime;
    #region Variables
    #region Connection with Rider Variables
    [Tooltip("Enable this if you want to control the horse alone, without requiring mounting")]
    public bool PlayerControlled;
    [Tooltip("This activate the animator layer that contains the horse's bones offset, in order to use the same animation. Custom is for use your own Horse Model")]
    public HorseMeshType horseType;
    [HideInInspector]
    public bool Mounted;
    [HideInInspector]
    public bool Mountedside;
    [HideInInspector]
    public Animator RiderAnimator; // Rider's Animatorto control both Sync animators from here
    #endregion
    #region Horse Components
    private Animator anim;
    private Rigidbody horseRigidBody;
    private BoxCollider horseCollider;
    private HashIDs hashs;  //Hash ID For the animator parameters
    private float scaleFactor;
    #endregion
    #region Animator Parameters Variables
    private float speed;
    private float direction;
    private float MaxSpeed = 1f; //1 Walking, 2 Trotting, 3 Cantering, 4 Galloping, 5 Sprinting
 
    //States Variables
    private bool
        galoping,
        trotting,
        swimming,
        flying, // Coming Soon Pegassus
        falling,
        fallingback,
        sleep,
        jump,
        Shift, //Cantering ,Sprint, turn 180
        attack,
        IsInWaterHip,
        IsInWater,
        stand,
        fowardPressed = false;
 
    private int sleepCount, horseInt;
    private float horizontal, vertical, horsefloat = , MaxHeight;
    private float jumpingCurve;
    #endregion
 
    [Header("Custom Options")]
    [Tooltip("Add more rotation to the turn animations")]
    [Range(, 100)]
    public float TurnSpeed = 5;
    [Tooltip("Amount of idle cycles before go to sleep state")]
    [Range(1, 100)]
    public int GoToSleep = 10;
    [Tooltip("Max Distance for the horse to recover from a big fall, Greater value: The horse will still running after falling from a great height")]
    [Range(1, 100)]
    public float recoverByFallDist;
    [Tooltip("Smoothness for snapping to ground, Higher value Harder Snap")]
    [Range(1, 100)]
    public float SnapToGround = 20f;
 
    [Header("Swim Options")]
    [Range(1, 10)]
    public float swimSpeed = 1f;
    [Range(1, 100)]
    public float SwimTurnSpeed = 1f;
 
    #region FixTransform_Variables
    RaycastHit hit_Hip, hit_Chest, WaterHitCenter;
    Vector3 Horse_Hip, Horse_Chest;
    Vector3 ErrorTresh = Vector3.up * 0.5f;
    float distanceHip;
    const float fallingMultiplier = 1.6f;
    float heightHorse;
    float WaterDistanceHip, distanceChest;
    float angleTerrain, inclination, fallheight;
    Pivots[] pivots;
    private Vector3 ColliderCenter;
    private Vector3 rigidVelocity;
    #endregion
    [Header("Keys for Horse Speed")]
    public KeyCode Walk = KeyCode.Alpha1;
    public KeyCode Trot = KeyCode.Alpha2;
    public KeyCode Gallop = KeyCode.Alpha3;
    [Header("Reference For Rider IKs Points")]
    #region Transform feet and mount on the Horse
    public Transform RidersLink;   // Reference for the RidersLink Bone
    public Transform LeftIK;       // Reference for the LeftFoot correct position on the mount
    public Transform RightIK;      // Reference for the RightFoot correct position on the mount
    public Transform LeftKnee;     // Reference for the LeftKnee correct position on the mount
    public Transform RightKnee;    // Reference for the RightKnee correct position on the mount
    #endregion
    #endregion
    #region Properies      
    public bool Stand
    {
        get { return this.stand; }
    }
    public float MaxFallHeight
    {
        set { fallheight = value; }
        get { return this.fallheight; }
    }
    public bool Sleep
    {
        set { sleep = value; }
    }
    public int SleepCount
    {
        set { sleepCount = value; }
        get { return this.sleepCount; }
    }
    public bool isFalling
    {
        // set { falling = value; }
        get { return this.falling; }
    }
    public int HorseInt
    {
        set { horseInt = value; }
        get { return this.horseInt; }
    }
    public float HorseFloat
    {
        set { horsefloat = value; }
        get { return this.horsefloat; }
    }
    #endregion
 
    // Use this for initialization
    void Start()
    {
       // Cursor.visible = false;
        anim = GetComponent<Animator>();
        hashs = GetComponent<HashIDs>();
       
        horseCollider = GetComponent<BoxCollider>();
        horseRigidBody = GetComponent<Rigidbody>();
        ColliderCenter = horseCollider.center;
        pivots = GetComponentsInChildren<Pivots>(); //Pivots are Strategically Transform objects use to cast rays used by the horse
        scaleFactor = transform.localScale.y;  //TOTALLY SCALABE HORSE
 
        heightHorse = pivots[].transform.localPosition.y * scaleFactor; // Height from Chest to ground
        anim.SetInteger("HorseType", (int)horseType); //Adjust the layer for the curret horse Type
        horseRigidBody.drag = ;
        horseRigidBody.angularDrag = 25f;
        sleepCount = ;
        //
    }
    //----------------------Link the buttons pressed with correspond variables-------------------------------------------------------------------------------
    void getButtons()
    {
        fowardPressed = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow); //If foward is pressed
        #if UNITY_ANDROID || UNITY_IOS
                if (CrossPlatformInputManager.GetAxis("Vertical") > )
                    fowardPressed = true;
                else fowardPressed = false;
        #endif
        attack = CrossPlatformInputManager.GetButtonDown("Fire1");            //Get the Attack button
        if (attack)
        {
            horseInt = Random.Range(, 3);                                         //Random Attack ID: ID identify the type of attack
            sleepCount = ;
        }
 
        horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
        vertical = CrossPlatformInputManager.GetAxis("Vertical");
        Shift = CrossPlatformInputManager.GetButton("Fire3");
       // Shift = Input.GetKey(KeyCode.LeftShift);
       
        #if UNITY_ANDROID || UNITY_IOS
         
        #endif
        //Get the Sprint/Cantering/Turn180 button
        jump = CrossPlatformInputManager.GetButtonDown("Jump");             //Get the Jump button
        if (Input.GetKeyDown(KeyCode.K))                                    //Get the Death button
        {
            horseInt = Random.Range(, 2);
        }
    }
    //----------------------linking  the Parameters Horse && Rider------------------------------------------------------------------------
    void LinkingAnimator(Animator anim_)
    {
        jumpingCurve = anim.GetFloat("JumpCurve");
        anim_.SetFloat(hashs.speedHash, speed*vertical);
        anim_.SetFloat(hashs.horizontalHash, direction);
        anim_.SetBool(hashs.shiftHash, Shift);
        anim_.SetBool(hashs.galopingHash, galoping);
        anim_.SetBool(hashs.trottingHash, trotting);
        anim_.SetBool(hashs.standHash, stand);
        anim_.SetBool(hashs.jumpHash, jump);
        anim_.SetBool(hashs.fowardHash, fowardPressed);
        anim_.SetBool(hashs.SwimHash, swimming);
        anim_.SetFloat(hashs.inclinationHash, inclination);
        anim_.SetBool(hashs.fallingHash, falling);
        anim_.SetBool(hashs.fallingBackHash, fallingback);
        anim_.SetBool(hashs.sleepHash, sleep);
        anim_.SetBool(hashs.attackHash, attack);
        anim_.SetInteger(hashs.IntHash, horseInt);
       
        if (falling || isJumping(1,true))
        {
            anim_.SetFloat(hashs.FloatHash, horsefloat);
        }
        if (Input.GetKeyDown(KeyCode.K))
        {
            anim_.SetTrigger(hashs.deathHash);
        }
 
    }
    //--Add more Rotations to the current turn animations  using the public turnSpeed float--------------------------------------------
    void TurnAmount()
    {
        //For going Foward and Backward
        if (vertical >= )
        {
           
            if (!swimming)
                transform.Rotate(transform.up, TurnSpeed * 3 * horizontal * Time.deltaTime);
            else
                transform.Rotate(transform.up, SwimTurnSpeed * 3 * horizontal * Time.deltaTime);
            //horseRigidBody.AddTorque((transform.up * horizontal) * TurnSpeed / 2 / Time.deltaTime);
        }
        else
        {
            if (!swimming)
            {
                transform.Rotate(transform.up, TurnSpeed * 3 * -horizontal * Time.deltaTime);
            }
            else
            {
                transform.Rotate(transform.up, SwimTurnSpeed * 3 * -horizontal * Time.deltaTime);
            }
            // horseRigidBody.AddTorque((transform.up * -horizontal) * TurnSpeed / 2 / Time.deltaTime);
        }
        //Add Speed to current animation foward swim
        if (swimming && vertical>)
        {
            transform.position = Vector3.Lerp(transform.position, transform.position + transform.forward * swimSpeed * vertical/2, Time.deltaTime);
        }
    }
 
    //--------The Collider is not touching the floor to avoid collision with small objects, Here the Height is fixed , Terrain Compatible----------
    void FixPosition()
    {
        //Position to cast a ray downward from the  Horse Chest and Horse Hip.
        Horse_Hip = pivots[].transform.position;
        Horse_Chest = pivots[1].transform.position;
        inclination = ((Horse_Chest.y - Horse_Hip.y) / 2) / scaleFactor;  //Calculate the inclination between front and rear legs\
        Vector3 JumpingCurve = new Vector3(, jumpingCurve, );
        //Ray From Horse Hip to the ground
        if (Physics.Raycast(Horse_Hip + JumpingCurve, -transform.up, out hit_Hip, (heightHorse + jumpingCurve) * fallingMultiplier * scaleFactor, LayerMask.GetMask("Default")))
        {
            Debug.DrawRay(Horse_Hip + JumpingCurve, -transform.up * heightHorse * scaleFactor * fallingMultiplier, Color.green);
            distanceHip = hit_Hip.distance - jumpingCurve;
        }
        else
        {
            fallingback = true;
        }
 
        //Ray From Horse Chest to the ground
        if (Physics.Raycast(Horse_Chest + JumpingCurve, -transform.up, out hit_Chest, (heightHorse + jumpingCurve) * fallingMultiplier * scaleFactor, LayerMask.GetMask("Default")))
        {
            distanceChest = hit_Chest.distance - jumpingCurve;
            Debug.DrawRay(Horse_Chest + JumpingCurve, -transform.up * heightHorse * scaleFactor * fallingMultiplier, Color.green);
        }
        else
        {
           falling = true;
           
        }
 

        //Front RayWater Cast
        if (Physics.Raycast(horseCollider.bounds.center + ErrorTresh+ JumpingCurve, -transform.up, out WaterHitCenter, heightHorse * scaleFactor*2, LayerMask.GetMask("Water")))
        {
            Debug.DrawRay(horseCollider.bounds.center + ErrorTresh + JumpingCurve, -transform.up * heightHorse * scaleFactor * 2, Color.blue);
           
            //if there nothing on top of the water
            if (hit_Chest.distance>WaterHitCenter.distance)
            {
                IsInWater = true;
            }
        }
        else
        {
            IsInWater = false;
        }
 

        //If the horse has  water near the Neck then start swimming
        if (WaterHitCenter.transform) //if we hit water
        {
            if (Horse_Chest.y < WaterHitCenter.transform.position.y && IsInWater)
            {
                swimming = true;
                falling = false;
            }
            if (IsInWater && distanceChest < 1f * scaleFactor)  //else stop swimming when he is coming out of the water
            {
               swimming = false;
               MaxSpeed = 1f;
               galoping = false;
               trotting = false;
            }
        }
 
        //-----------------------------water Adjusment-------------------------------------------
        if (swimming)
        {
            falling = false;
            fallingback = false;
            horseRigidBody.constraints = RigidbodyConstraints.FreezeRotationZ | RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezePositionY;
            float angleWater = Vector3.Angle(transform.up, Vector3.up);
            Quaternion finalRot = Quaternion.FromToRotation(transform.up, Vector3.up) * horseRigidBody.rotation;
            //Smoothy rotate until is Aling with the Water
            if (angleWater > 0.1f)
                transform.rotation = Quaternion.Lerp(transform.rotation, finalRot, Time.deltaTime * 10);
            else
                transform.rotation = finalRot;
            //Smoothy Move until is Aling with the Water
            if (WaterHitCenter.transform)
                transform.position = Vector3.Lerp(transform.position, new Vector3(transform.position.x, WaterHitCenter.transform.position.y - heightHorse, transform.position.z), Time.deltaTime * 5f);
        }
        else
        {
            //------------------------------------------------Terrain Adjusment-----------------------------------------
            //----------Calculate the Align vector of the terrain------------------
            Vector3 direction = (hit_Chest.point - hit_Hip.point).normalized;
            Vector3 Side = Vector3.Cross(Vector3.up, direction).normalized;
            Vector3 SurfaceNormal = Vector3.Cross(direction, Side).normalized;
            angleTerrain = Vector3.Angle(transform.up, SurfaceNormal);
            // ------------------------------------------Orient To Terrain-----------------------------------------  
            Quaternion finalRot = Quaternion.FromToRotation(transform.up, SurfaceNormal) * horseRigidBody.rotation;
            // If the horse is falling smoothly aling with the horizontal
            if ((isJumping(0.55f, true)) || fallingback)
            {
                finalRot = Quaternion.FromToRotation(transform.up, Vector3.up) * horseRigidBody.rotation;
                transform.rotation = Quaternion.Lerp(transform.rotation, finalRot, Time.deltaTime * 5f);
            }
            else
            {
                // if the terrain changes hard smoothly adjust to the terrain
                if (angleTerrain > 2 && !stand)
                {
                    transform.rotation = Quaternion.Lerp(transform.rotation, finalRot, Time.deltaTime * 10f);
                }
                else
                {
                    transform.rotation = finalRot;
                }
            }
            float distance = distanceHip;
            float realsnap = SnapToGround; // changue in the inspector the  adjusting speed for the terrain
            if (isJumping(0.5f, false)) //Calculate from the front legss
            {
                //calculate the adjust distance from the front legs if is finishing jumping. Solution for jumping High places at the same distance
                 distance = distanceChest;
                realsnap = SnapToGround / 4;
            }
            //-----------------------------------------Snap To Terrain-------------------------------------------
            if (distance != heightHorse)
            {
                float diference = heightHorse - distance;
                transform.position = Vector3.Lerp(transform.position, transform.position + new Vector3(, diference, ), Time.deltaTime * realsnap);
            }
        }
    }
    public void Falling()
    {
        //if the horse stay stucked while falling move foward  ... basic solution
        if (falling && horseRigidBody.velocity.magnitude<0.1 && !swimming)
        {
            transform.position = Vector3.Lerp(transform.position, transform.position + transform.forward*2, Time.deltaTime);
        }
 
        RaycastHit offGround; //Front Falling Ray
        Vector3 FallingVectorFront = pivots[2].transform.position; // get the Transform Falling from vector within the horse hierarchy
        Debug.DrawRay(FallingVectorFront, -transform.up * heightHorse * fallingMultiplier, Color.blue);
        //Ignore Layer Horse 20
        var layermask = 1 << 20;
        layermask = ~layermask;
        if (Physics.Raycast(FallingVectorFront, -transform.up, out offGround, heightHorse * fallingMultiplier,layermask))
        {
            //---------------------Finding the water while falling------------------------
            if (offGround.transform.gameObject.layer == 4) //4 is Water layer
            {
                if (offGround.transform) //if we hit water
                {
                    IsInWater =
#42
General (Antiguo) / Reiniciar un nivel.
Septiembre 02, 2016, 01:52:03 PM
Que frustamiento...nada funciona,he provado a ponerle un debug log para ver si llegaba a hacer el bank y si lo hace , pero no envia el ,mensaje mas alla osea ni apaga ni enciende las luces ni aumenta el porcentaje.Incluso la bola extra funciona simpre que tembien esta en este script...
 
tiene que ser algo de este script:
 
por favor echadle un ojo...no se que mas hacer :(
 
Este el el que controla los puntos y los x2 y x3:
 
 
 

using UnityEngine;
using System.Collections;
public class ScoreManager : MonoBehaviour
{
public static ScoreManager Instance;
void Awake()
{
Instance = this;
}
public   int score =;
public   int scorePower = 2;
public   int bankvalue =10000;
public    TextMesh display;
public GameObject Ballmanager;
private bool detener;
private bool extra;
private int nextExtraBall = ;
public int scoreExtraBall = 10000;
public GameObject Extraball;
public AudioClip extrabolaaudio;
AudioSource audio;
 
void Start()
{
   nextExtraBall += scoreExtraBall;
   audio = GetComponent<AudioSource>();
}
 
void Update()
{
   if(extra){
      Extraball.SetActive (true);
   }
   if (display)
   {
      display.text = score.ToString ("D8");
   }
   if (score >= nextExtraBall && detener == false) {
   millonn();
   nextExtraBall += scoreExtraBall;
  // extra = true;
   Extraball.SetActive(true);
   audio.PlayOneShot(extrabolaaudio, 0.7F);
   Invoke ("apaga", 4);
}   
}
public   void ScoreUp(int points)
{
score += (points * scorePower);
}
public  void SetScorePower(int power)
{
   scorePower = power;
}
void millonn()
{
Debug.Log ("MILLLOOOOONNN");
Ballmanager.GetComponent<BallManager> ().lives += 1;
}
void apaga()
{
   //extra = false;
   Extraball.SetActive(false);
}
}
 

 
y estos los que dan problemas :
 
1:
 

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

   public float dropDistance = 1.0f;
   public int bankID = ;
   public float resetDelay = 0.5f;
   public static List<letrasderecha> dropTargets = new List<letrasderecha>();
   public int targetValue = 100;
   public int bankValue = 10000;
   AudioSource audio;
   public AudioClip sonidotarget;   
   public bool isDropped = false;
   public  GameObject TextOnSpotGO;
    public AudioClip duel;
    public GameObject luzx1;
    public GameObject luzx2;
    public GameObject luzx3;
    public int cantidadx =;
   
   void Start ()
   {
      dropTargets.Add(this);
      audio = GetComponent<AudioSource>();
       luzx3.SetActive (false);
   }
         
   void OnCollisionEnter()
   {
      if(!isDropped)
      {
         //Drop Target
         transform.position += Vector3.down*dropDistance;
         isDropped = true;
         ScoreManager.Instance.ScoreUp(targetValue);
         GameObject textInstance = Instantiate (TextOnSpotGO, transform.position, Quaternion.identity) as GameObject;
         textInstance.GetComponent<TextOnSpotScript>().DisplayText = targetValue * ScoreManager.Instance.scorePower + "";
          audio.PlayOneShot(sonidotarget, 0.7F);
         //Check to see if the rest of the bank has been dropped
         bool resetBank = true;
         foreach(letrasderecha target in dropTargets)
         {
            if(target.bankID == bankID)
            {
               if(!target.isDropped)
               {
                  resetBank = false;
               }
            }
         }
         //Reset all drop targets in bank if the bank has been dropped
         if(resetBank)
         {
            //ScoreManager.Instance.score += bankValue;
             Debug.Log("TODOS ABAJO");
            ScoreManager.Instance.ScoreUp(bankValue);///(scoreValue);
            Instantiate (TextOnSpotGO, transform.position, Quaternion.identity);
            //TextOnSpotGO.GetComponent<TextOnSpotScript>().DisplayText = ScoreManager.Instance.bankvalue * ScoreManager.Instance.scorePower + "";
             textInstance.GetComponent<TextOnSpotScript>().DisplayText = bankValue * ScoreManager.Instance.scorePower + "";
            Invoke("ResetBank", resetDelay);
             audio.PlayOneShot(duel, 0.7F);
             ScoreManager.Instance.SetScorePower (cantidadx);
             luzx3.SetActive (true);
             luzx2.SetActive (false);
             luzx1.SetActive (false);
         }
      }
   }
   void ResetBank()
   {
      foreach(letrasderecha target in dropTargets)
      {
         if(target.bankID == bankID)
         {
            target.transform.position += Vector3.up*dropDistance;
            target.isDropped = false;
         }
      }
   }
}

 
2:
 

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class letras : MonoBehaviour {
public float dropDistance = 1.0f;
public int bankID = ;
public float resetDelay = 0.5f;
public static List<letras> dropTargets2 = new List<letras>();
public int targetValue = 100;
public int bankValue = 10000;
AudioSource audio;
public AudioClip sonidotarget;   
public bool isDropped = false;
public  GameObject TextOnSpotGO;
public AudioClip duel;
public GameObject luzx1;
public GameObject luzx2;
public GameObject luzx3;
public int cantidadx =;
 
void Start ()
{
   dropTargets2.Add(this);
   audio = GetComponent<AudioSource>();
   luzx3.SetActive (false);
}
 
void OnCollisionEnter()
{
   if(!isDropped)
   {
      //Drop Target
      transform.position += Vector3.down*dropDistance;
      isDropped = true;
      ScoreManager.Instance.ScoreUp(targetValue);
      GameObject textInstance = Instantiate (TextOnSpotGO, transform.position, Quaternion.identity) as GameObject;
      textInstance.GetComponent<TextOnSpotScript>().DisplayText = targetValue * ScoreManager.Instance.scorePower + "";
      audio.PlayOneShot(sonidotarget, 0.7F);
      //Check to see if the rest of the bank has been dropped
      bool resetBank = true;
      foreach(letras target in dropTargets2)
      {
         if(target.bankID == bankID)
         {
            if(!target.isDropped)
            {
               resetBank = false;
            }
         }
      }
 
      if(resetBank)
      {
         //ScoreManager.Instance.score += bankValue;
         Debug.Log("TODOS ABAJO");
         ScoreManager.Instance.ScoreUp(bankValue);///(scoreValue);
         Instantiate (TextOnSpotGO, transform.position, Quaternion.identity);
         //TextOnSpotGO.GetComponent<TextOnSpotScript>().DisplayText = ScoreManager.Instance.bankvalue * ScoreManager.Instance.scorePower + "";
         textInstance.GetComponent<TextOnSpotScript>().DisplayText = bankValue * ScoreManager.Instance.scorePower + "";
         Invoke("ResetBank", resetDelay);
         audio.PlayOneShot(duel, 0.7F);
         ScoreManager.Instance.SetScorePower (cantidadx);
         luzx3.SetActive (false);
         luzx2.SetActive (true);
         luzx1.SetActive (false);
      }
   }
}
void ResetBank()
{
   foreach(letras target in dropTargets2)
   {
      if(target.bankID == bankID)
      {
         target.transform.position += Vector3.up*dropDistance;
         target.isDropped = false;
      }
   }
}
}

 
He añadido esto:
 

using UnityEngine;
using System.Collections;
public class dontdestroy : MonoBehaviour {
void Start()
{
   if(GameObject.Find(this.gameObject.name) && GameObject.Find(this.gameObject.name) != this.gameObject )
   
   {
      Destroy(gameObject);
    }
else
   {
   DontDestroyOnLoad(this.gameObject);
   }
}
 
}

 
para asegurarme de que se destruye...pero sigue igual.Igual ,e refiero que al empezar ba de lujo hasta que se acaban las vidas y se resetea luego ya no funciona.
 
Bueno algo nuevo, si solo pongo un script de los dos funciona bien en este caso letrasderecha...se interferirán unos con otros?
 
 
#43
General (Antiguo) / Reiniciar un nivel.
Septiembre 02, 2016, 12:26:17 AM
iRobb gracias por la respuesta , si eso es un singleton...puede ser de alli?
 
y como se si se destruie?
 
provare a quitarle el singleton....aver si me lo cargo todo XD
 
Val he quitado el
 
singleton y puesto las vriables estaticas para poder acceder a ellas...
 

public   static int score =;
public   static int scorePower = 2;
//public   int bankvalue =10000;
public    TextMesh display;
public GameObject Ballmanager;
private bool detener;
private bool extra;
private int nextExtraBall = ;
public int scoreExtraBall = 10000;
public GameObject Extraball;
public AudioClip extrabolaaudio;
AudioSource audio;

 
mismo resultado
 
al reiniciar la escena funciona solo parcialmente (
 
 
#44
General (Antiguo) / Reiniciar un nivel.
Septiembre 01, 2016, 11:45:29 PM
elamguido, gracias por la respuesta , no tengo ningun dontdestroy ni variables estaticas...
 
Es muy raro, pero raro raro, cuando empieza el juego todo va bien,luego al resetear el nivel solo este objeto funciona parcialmente.....
 
 
#45
General (Antiguo) / Reiniciar un nivel.
Septiembre 01, 2016, 05:20:36 PM
Buenas tardes, tengo un pequeño y espero decir pequeño porque seria una ***a...problemilla.
 
Tengo un proyecto de juego que solo tiene una escena.
 
Bien si la palmas te sale el típico botón reiniciar.
 
bien el juego empieza de nuevo pero....algunos scripts o componentes no reaccionan / funcionan adecuadamente como si se cargaran mal.Estoy usando el ultimo Unity y creo que he probado todas las maneras de reiniciar el nivel:
 

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class gameover : MonoBehaviour {
 

public void reiniciar()
{
//SceneManager.LoadScene("mesapinball"); ////ESTA NO VA BIEN
//   Application.LoadLevel (Application.loadedLevelName);//ESTA TAMPOCO....
SceneManager.LoadScene(SceneManager.GetActiveScene().name);///TAMPOCO
Time.timeScale = 1.0F;
}
   
public void salir()
{
Application.Quit();
}
}

 
todas lo reinician pero omitiendo trozos....debería meter un dontdestroy a todo lo que no funciona?
 
 
 
Sabéis de otra manera para que se cargue todo?
 
EDITO;
 
el que no se carga de nuevo al hacer el restart es peculiarmente este:
 

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class droptargetss : MonoBehaviour {
public float dropDistance = 1.0f;
public int bankID = ;
public float resetDelay = 0.5f;
public static List<droptargetss> dropTargets = new List<droptargetss>();
public int targetValue = 100;
public int bankValue = 10000;
AudioSource audio;
public AudioClip sonidotarget;   
public AudioClip cantina;   
public bool isDropped = false;
public GameObject luzx1;
public GameObject luzx2;
public  GameObject TextOnSpotGO;
//public GameObject cantinavideo;
 
//   void Awake() {
//      DontDestroyOnLoad(transform.gameObject);
//   }
// Use this for initialization
void Awake ()
{
   dropTargets.Add(this);
   audio = GetComponent<AudioSource>();
   luzx2.SetActive (false);
}
// Update is called once per frame
void Update ()
{
}
void OnCollisionEnter()
{
   if(!isDropped)
   {
      //Drop Target
      transform.position += Vector3.down*dropDistance;
      isDropped = true;
      ScoreManager.Instance.ScoreUp(targetValue);
      GameObject textInstance = Instantiate (TextOnSpotGO, transform.position, Quaternion.identity) as GameObject;
      textInstance.GetComponent<TextOnSpotScript>().DisplayText = targetValue * ScoreManager.Instance.scorePower + "";
      //         ScoreManager.Instance.ScoreUp(targetValue);
      //         //ScoreManager.Instance.ScoreUp(scoreValue);
      //         Instantiate (TextOnSpotGO, transform.position, Quaternion.identity);
      //         TextOnSpotGO.GetComponent<TextOnSpotScript>().DisplayText = ScoreManager.Instance.scoretarjets * ScoreManager.Instance.scorePower + "";
      audio.PlayOneShot(sonidotarget, 0.7F);
 
      //Check to see if the rest of the bank has been dropped
      bool resetBank = true;
      foreach(droptargetss target in dropTargets)
      {
         if(target.bankID == bankID)
         {
            if(!target.isDropped)
            {
               resetBank = false;
            }
         }
      }
      //Reset all drop targets in bank if the bank has been dropped
      if(resetBank)
      {
         //ScoreManager.Instance.score += bankValue;
         ScoreManager.Instance.ScoreUp(bankValue);///(scoreValue);
         Instantiate (TextOnSpotGO, transform.position, Quaternion.identity);
         TextOnSpotGO.GetComponent<TextOnSpotScript>().DisplayText = ScoreManager.Instance.bankvalue * ScoreManager.Instance.scorePower + "";
         Invoke("ResetBank", resetDelay);
         ScoreManager.Instance.SetScorePower (2);
         audio.PlayOneShot(cantina, 0.7F);
         //cantinavideo.SetActive (true);
         luzx2.SetActive (true);
         luzx1.SetActive (false);
      }
   }
}
void ResetBank()
{
   foreach(droptargetss target in dropTargets)
   {
      if(target.bankID == bankID)
      {
         target.transform.position += Vector3.up*dropDistance;
         target.isDropped = false;
      }
   }
}
}

 
Alguna idea?
 
He probado con dont destroy pero al reiniciar el nivel se duplica...