Ejemplo n.º 1
0
        public static Vector3[] computeCorners(Auto auto)
        {
            TgcObb obbAuto = auto.obb;

            Vector3[] corners = new Vector3[8];
            Vector3   extents;

            Vector3[] orientation = obbAuto.Orientation;
            Vector3   center      = obbAuto.Center;

            extents = auto.mesh.BoundingBox.calculateAxisRadius();
            extents = TgcVectorUtils.abs(extents);

            Vector3 eX = extents.X * orientation[0];
            Vector3 eY = extents.Y * orientation[1];
            Vector3 eZ = extents.Z * orientation[2];

            corners[0] = center - eX - eY - eZ;
            corners[1] = center - eX - eY + eZ;

            corners[2] = center - eX + eY - eZ;
            corners[3] = center - eX + eY + eZ;

            corners[4] = center + eX - eY - eZ;
            corners[5] = center + eX - eY + eZ;

            corners[6] = center + eX + eY - eZ;
            corners[7] = center + eX + eY + eZ;

            return(corners);
        }
        public HollowObbCollider(TgcMesh mesh, Vector3 minCornerScale, Vector3 maxCornerScale)
        {
            var obb = TgcObb.computeFromAABB(mesh.BoundingBox);

            _HollowObbCollider(obb, obb.Center - mesh.Position, minCornerScale, maxCornerScale);
            obb.dispose();
        }
Ejemplo n.º 3
0
        public override void init()
        {
            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;

            //Cuerpo principal que se controla con el teclado
            box = TgcBox.fromSize(new Vector3(0, 10, 0), new Vector3(10, 10, 10), Color.Blue);

            //triangulo
            triangle    = new CustomVertex.PositionColored[3];
            triangle[0] = new CustomVertex.PositionColored(-100, 0, 0, Color.Red.ToArgb());
            triangle[1] = new CustomVertex.PositionColored(0, 0, 50, Color.Green.ToArgb());
            triangle[2] = new CustomVertex.PositionColored(0, 100, 0, Color.Blue.ToArgb());
            triagleAABB = TgcBoundingBox.computeFromPoints(new Vector3[] { triangle[0].Position, triangle[1].Position, triangle[2].Position });

            //box2
            box2 = TgcBox.fromSize(new Vector3(-50, 10, -20), new Vector3(15, 15, 15), Color.Violet);

            //sphere
            sphere = new TgcBoundingSphere(new Vector3(30, 20, -20), 15);

            //OBB: computar OBB a partir del AABB del mesh.
            TgcSceneLoader loader  = new TgcSceneLoader();
            TgcMesh        meshObb = loader.loadSceneFromFile(GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Meshes\\Vehiculos\\StarWars-ATST\\StarWars-ATST-TgcScene.xml").Meshes[0];

            obb = TgcObb.computeFromAABB(meshObb.BoundingBox);
            meshObb.dispose();
            obb.move(new Vector3(100, 0, 30));
            obb.setRotation(new Vector3(0, FastMath.PI / 4, 0));


            //Configurar camara en Tercer Persona
            GuiController.Instance.ThirdPersonCamera.Enable = true;
            GuiController.Instance.ThirdPersonCamera.setCamera(box.Position, 30, -75);
        }
Ejemplo n.º 4
0
        public static void updateObbFromSegment(TgcObb obb, Vector3 a, Vector3 b, float thickness)
        {
            Vector3 lineDiff   = b - a;
            float   lineLength = lineDiff.Length();
            Vector3 lineVec    = Vector3.Normalize(lineDiff);

            //Obtener angulo y vector de rotacion
            Vector3 upVec        = new Vector3(0, 1, 0);
            float   angle        = FastMath.Acos(Vector3.Dot(upVec, lineVec));
            Vector3 axisRotation = Vector3.Cross(upVec, lineVec);

            axisRotation.Normalize();

            //Obtener matriz de rotacion para este eje y angulo
            Matrix rotM = Matrix.RotationAxis(axisRotation, angle);

            //Actualizar orientacion de OBB en base a matriz de rotacion
            obb.Orientation[0] = new Vector3(rotM.M11, rotM.M12, rotM.M13);
            obb.Orientation[1] = new Vector3(rotM.M21, rotM.M22, rotM.M23);
            obb.Orientation[2] = new Vector3(rotM.M31, rotM.M32, rotM.M33);

            //Actualizar extent de OBB segun el thickness del segmento
            obb.Extents = new Vector3(thickness, lineLength / 2, thickness);

            //Actualizar centro del OBB segun centro del segmento
            obb.Center = a + Vector3.Scale(lineDiff, 0.5f);

            //Regenerar OBB
            obb.updateValues();
        }
Ejemplo n.º 5
0
        public override void init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

            //Cargar modelo
            TgcSceneLoader loader = new TgcSceneLoader();
            TgcScene       scene  = loader.loadSceneFromFile(
                GuiController.Instance.ExamplesMediaDir + "MeshCreator\\Meshes\\Vehiculos\\StarWars-ATST\\StarWars-ATST-TgcScene.xml");

            mesh = scene.Meshes[0];

            //Computar OBB a partir del AABB del mesh. Inicialmente genera el mismo volumen que el AABB, pero luego te permite rotarlo (cosa que el AABB no puede)
            obb = TgcObb.computeFromAABB(mesh.BoundingBox);

            //Otra alternativa es computar OBB a partir de sus vertices. Esto genera un OBB lo mas apretado posible pero es una operacion costosa
            //obb = TgcObb.computeFromPoints(mesh.getVertexPositions());



            //Alejar camara rotacional segun tamaño del BoundingBox del objeto
            GuiController.Instance.RotCamera.targetObject(mesh.BoundingBox);


            //Modifier para poder rotar y mover el mesh
            GuiController.Instance.Modifiers.addFloat("rotation", 0, 360, 0);
            GuiController.Instance.Modifiers.addVertex3f("position", new Vector3(0, 0, 0), new Vector3(50, 50, 50), new Vector3(0, 0, 0));
        }
Ejemplo n.º 6
0
        //OBB
        private List <TgcObb> cargarObbObjetos()
        {
            string        filePath  = GuiController.Instance.AlumnoEjemplosMediaDir + "TheC#\\Auto\\\\pistaObbs-TgcScene.xml";
            string        mediaPath = filePath.Substring(0, filePath.LastIndexOf('\\') + 1);
            string        xmlString = File.ReadAllText(filePath);
            List <TgcObb> objetos   = new List <TgcObb>();

            XmlDocument dom = new XmlDocument();

            dom.LoadXml(xmlString);
            XmlElement root = dom.DocumentElement;

            //Parsear obbs
            XmlNodeList obbNodes = root.GetElementsByTagName("obbs")[0].ChildNodes;

            foreach (XmlElement obbNode in obbNodes)
            {
                Vector3 center       = TgcParserUtils.float3ArrayToVector3(TgcParserUtils.parseFloat3Array(obbNode.Attributes["center"].InnerText));
                Vector3 extents      = TgcParserUtils.float3ArrayToVector3(TgcParserUtils.parseFloat3Array(obbNode.Attributes["extents"].InnerText));
                Vector3 orientation0 = TgcParserUtils.float3ArrayToVector3(TgcParserUtils.parseFloat3Array(obbNode.Attributes["orientation0"].InnerText));
                Vector3 orientation1 = TgcParserUtils.float3ArrayToVector3(TgcParserUtils.parseFloat3Array(obbNode.Attributes["orientation1"].InnerText));
                Vector3 orientation2 = TgcParserUtils.float3ArrayToVector3(TgcParserUtils.parseFloat3Array(obbNode.Attributes["orientation2"].InnerText));

                Vector3[] orientation = new Vector3[] { orientation0, orientation1, orientation2 };
                TgcObb    minObb      = new TgcObb();

                minObb.Center      = center;
                minObb.Extents     = extents;
                minObb.Orientation = orientation;

                objetos.Add(minObb);
            }

            return(objetos);
        }
        public HollowObbCollider(TgcBoundingBox bb, Vector3 translation, Vector3 minCornerScale, Vector3 maxCornerScale)
        {
            var obb = TgcObb.computeFromAABB(bb);

            _HollowObbCollider(obb, translation, minCornerScale, maxCornerScale);
            obb.dispose();
        }
        private void _HollowObbCollider(TgcObb obb, Vector3 translation, Vector3 minCornerScale, Vector3 maxCornerScale)
        {
            var e   = obb.Extents;
            var o   = obb.Orientation;
            var min = e.MemberwiseMult(minCornerScale);

            if (min.X > 0)
            {
                _AddCollider(o, new Vector3(min.X, e.Y, e.Z), (e.X - min.X) * Vector3Extension.Left + translation);
            }
            if (min.Y > 0)
            {
                _AddCollider(o, new Vector3(e.X, min.Y, e.Z), (e.Y - min.Y) * Vector3Extension.Bottom + translation);
            }
            if (min.Z > 0)
            {
                _AddCollider(o, new Vector3(e.X, e.Y, min.Z), (e.Z - min.Z) * Vector3Extension.Back + translation);
            }
            var max = e.MemberwiseMult(maxCornerScale);

            if (max.X > 0)
            {
                _AddCollider(o, new Vector3(max.X, e.Y, e.Z), (e.X - max.X) * Vector3Extension.Right + translation);
            }
            if (max.Y > 0)
            {
                _AddCollider(o, new Vector3(e.X, max.Y, e.Z), (e.Y - max.Y) * Vector3Extension.Top + translation);
            }
            if (max.Z > 0)
            {
                _AddCollider(o, new Vector3(e.X, e.Y, max.Z), (e.Z - max.Z) * Vector3Extension.Front + translation);
            }
        }
Ejemplo n.º 9
0
 public Checkpoint(float x, float z, float y, TgcMesh _modelo)
 {
     _modelo.Position  = new Vector3(x, y, z);
     this.modelo       = _modelo;
     this.modelo.Scale = new Vector3(5, 5, 5);
     this.obb          = TgcObb.computeFromAABB(this.modelo.BoundingBox);
 }
Ejemplo n.º 10
0
 public ObstaculoRigido(string _pathMesh, Vector3 _posicion, Vector3 _escala)
 {
     this.mesh          = MeshUtils.loadMesh(_pathMesh);
     this.mesh.Position = _posicion;
     this.mesh.Scale    = _escala;
     this.obb           = TgcObb.computeFromAABB(this.mesh.BoundingBox);
 }
Ejemplo n.º 11
0
        public static Vector3 ToObbSpace(this  Vector3 p, TgcObb obb)
        {
            var t = p - obb.Center;
            var o = obb.Orientation;

            return(new Vector3(Vector3.Dot(t, o[0]), Vector3.Dot(t, o[1]), Vector3.Dot(t, o[2])));
        }
Ejemplo n.º 12
0
 public static Vector3 ClosestPoint(this TgcObb obb, Vector3 p)
 {
     return(p
            .ToObbSpace(obb)
            .Clamp(-obb.Extents, obb.Extents)
            .FromObbSpace(obb));
 }
Ejemplo n.º 13
0
 public static void SetOrientation(this TgcObb obb, Matrix rotation)
 {
     obb.SetOrientation(
         new Vector3(rotation.M11, rotation.M12, rotation.M13),
         new Vector3(rotation.M21, rotation.M22, rotation.M23),
         new Vector3(rotation.M31, rotation.M32, rotation.M33)
         );
 }
Ejemplo n.º 14
0
        public override void Init()
        {
            obb = new TgcObb();
            generateObb();
            generate = false;

            Modifiers.addButton("generate", "generate", random_clic);
        }
Ejemplo n.º 15
0
        public override void init()
        {
            Device d3dDevice = GuiController.Instance.D3dDevice;

            obb = new TgcObb();
            generateObb();
            generate = false;

            GuiController.Instance.Modifiers.addButton("generate", "generate", new EventHandler(this.random_clic));
        }
Ejemplo n.º 16
0
        // Constructor
        public ObstaculoRigido(float _x, float _z, float _y, float ancho, float alto, float largo, string textura)
        {
            TgcBox box = TgcBox.fromSize(
                new Vector3(_x, _z, _y),           //posicion
                new Vector3(ancho, alto, largo),   //tamaño
                TgcTexture.createTexture(textura));

            //Computar OBB a partir del AABB del mesh. Inicialmente genera el mismo volumen que el AABB, pero luego te permite rotarlo (cosa que el AABB no puede)
            this.obb  = TgcObb.computeFromAABB(box.BoundingBox);
            this.mesh = box.toMesh("caja");
        }
Ejemplo n.º 17
0
 //no borren el metodo HuboCollision
 public bool huboColision(TgcObb obbDeUnAuto)
 {
     for (int i = 0; i < objetosColisionables.Count; i++)
     {
         if (Colisiones.testObbObb2(obbDeUnAuto, objetosColisionables[i]))
         {
             return(true);
         }
     }
     return(false);
 }
Ejemplo n.º 18
0
        public void reiniciar()
        {
            Vector3 posicionInicio = posicionInicial;

            this.velocidadActual   = 0;
            this.velocidadRotacion = velocidadRotacionOriginal;
            restaurarVertices();
            this.velocidadMaxima = this.velocidadMaximaInicial;
            this.mesh.Rotation   = rotacionInicial;
            this.mesh.Position   = posicionInicio;
            this.obb             = TgcObb.computeFromAABB(this.mesh.BoundingBox);
        }
Ejemplo n.º 19
0
        public static Matrix GetOrientation(this TgcObb obb)
        {
            var o = obb.Orientation;

            return(new Matrix()
            {
                M11 = o[0].X, M12 = o[0].Y, M13 = o[0].Z,
                M21 = o[1].X, M22 = o[1].Y, M23 = o[1].Z,
                M31 = o[2].X, M32 = o[2].Y, M33 = o[2].Z,
                M44 = 1,
            });
        }
Ejemplo n.º 20
0
        public Cannon()
        {
            var bodyMesh = Game.Current.GetMesh("Cannon");

            _LoadColider = new ObbCollider()
            {
                Extents = _LoadColiderExtents,
                Color   = ItemPart.DefaultPartColor,
            };
            Add(_LoadColider as ItemPart);
            Add(new MeshStaticPart(bodyMesh));
            var bodyObb = TgcObb.computeFromAABB(bodyMesh.BoundingBox);
            var bodyE   = bodyObb.Extents;

            bodyObb.Extents = new Vector3(bodyE.X * _BodyObbScaleY, bodyE.Y, bodyE.Z * _BodyObbScaleY);
            Add(new HollowObbCollider(bodyObb, bodyObb.Position - bodyMesh.Position, _MinBorderScale, _MaxBorderScale));
            bodyObb.dispose();

            var baseMesh = Game.Current.GetMesh("CannonBase");
            var baseObb  = TgcObb.computeFromAABB(baseMesh.BoundingBox);
            var baseE    = baseObb.Extents;

            baseObb.Extents   = new Vector3(baseE.X, baseE.Y * _BaseObbScaleY, baseE.Z);
            Add(_Base         = new MeshUnRotatedPart(baseMesh));
            Add(_BaseCollider = new ObbTranslatedUnRotatedCollider(baseObb, _BaseObbTranslation));

            Add(_Smoke = new TranslatedParticlePart()
            {
                Translation = new Vector3(0, 33, -4),
                Sound       = Game.Current.GetSound("Cannon.wav", EffectVolume),
                Animation   = new AnimatedQuad()
                {
                    Texture      = Game.Current.GetParticle("ExplosionGrey.png"),
                    FrameSize    = new Size(146, 146),
                    Size         = new Vector2(25, 25),
                    FirstFrame   = 2,
                    CurrentFrame = 2,
                    FrameRate    = 15,
                    TotalFrames  = 47,
                }
            });
            RotationChanged += Cannon_RotationChanged;
            _ChargeSound     = Game.Current.GetSound("CannonCharge.wav", 0);
        }
Ejemplo n.º 21
0
        public Auto(string pathMeshAuto, string _nombre, Vector3 _posicionInicial, float _velocidadMaxima, float _velocidadRotacion, float _aceleracion, float _masa, Vector3 _escala, Vector3 _rotacionInicial)
        {
            this.nombre          = _nombre;
            this.posicionInicial = _posicionInicial;
            this.mesh            = MeshUtils.loadMesh(pathMeshAuto);
            // sceneAuto = loadMesh(pathMeshAuto);
            //this.mesh = sceneAuto.Meshes[0];
            this.mesh.Scale      = _escala;
            this.rotacionInicial = _rotacionInicial;
            this.backupVertices();
            this.velocidadActual           = 0;
            this.velocidadMaxima           = _velocidadMaxima;
            this.velocidadMaximaInicial    = _velocidadMaxima;
            this.velocidadRotacion         = _velocidadRotacion;
            this.velocidadRotacionOriginal = _velocidadRotacion;
            this.masa        = _masa;
            this.aceleracion = _aceleracion;
            //Computar OBB a partir del AABB del mesh. Inicialmente genera el mismo volumen que el AABB, pero luego te permite rotarlo (cosa que el AABB no puede)
            this.obb = TgcObb.computeFromAABB(this.mesh.BoundingBox);

            this.puntoChoque = this.obb.Center;
            this.direccion   = new TgcArrow();
            direccion.PStart = this.obb.Center;
            Vector3 rotacion = this.mesh.Rotation;

            direccion.PEnd = this.obb.Center + Vector3.Multiply(new Vector3(rotacion.X, rotacion.Y, rotacion.Z), 500f);

            //// acá defino un mesh auxiliar para probar con el Debug mode
            string         sphere = GuiController.Instance.ExamplesMediaDir + "ModelosTgc\\Sphere\\Sphere-TgcScene.xml";
            TgcSceneLoader loader = new TgcSceneLoader();

            moon       = loader.loadSceneFromFile(sphere).Meshes[0];
            moon.Scale = new Vector3(0.6f, 0.6f, 0.6f);

            //le asignamos una cantidad de chispas cada vez que choca
            for (int i = 0; i < cantidadDeChispas; i++)
            {
                chispas.Add(new Chispa());
            }

            //... y un poco de sonido a los choques
            this.sonidoChoque = new Sonido(Shared.mediaPath + "\\sonidos\\choque.wav");
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Crea un array con los 8 vertices del OBB
        /// </summary>
        private Vector3[] computeCorners(TgcObb obb)
        {
            Vector3[] corners = new Vector3[8];

            Vector3 eX = obb.Extents.X * obb.Orientation[0];
            Vector3 eY = obb.Extents.Y * obb.Orientation[1];
            Vector3 eZ = obb.Extents.Z * obb.Orientation[2];

            corners[0] = obb.Center - eX - eY - eZ;
            corners[1] = obb.Center - eX - eY + eZ;

            corners[2] = obb.Center - eX + eY - eZ;
            corners[3] = obb.Center - eX + eY + eZ;

            corners[4] = obb.Center + eX - eY - eZ;
            corners[5] = obb.Center + eX - eY + eZ;

            corners[6] = obb.Center + eX + eY - eZ;
            corners[7] = obb.Center + eX + eY + eZ;

            return(corners);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Crear nube de puntos aleatorios y luego computar el mejor OBB que los ajusta
        /// </summary>
        private void generateObb()
        {
            obb.dispose();
            obb = null;

            //Crear nube ed puntos
            int   COUNT    = 10;
            float MIN_RAND = -20f;
            float MAX_RAND = 20f;

            points = new Vector3[COUNT];
            for (int i = 0; i < points.Length; i++)
            {
                float x = MIN_RAND + (float)rand.NextDouble() * (MAX_RAND - MIN_RAND);
                float y = MIN_RAND + (float)rand.NextDouble() * (MAX_RAND - MIN_RAND);
                float z = MIN_RAND + (float)rand.NextDouble() * (MAX_RAND - MIN_RAND);
                points[i] = new Vector3(x, y, z);
            }

            //Computar mejor OBB
            obb = TgcObb.computeFromPoints(points);



            if (vertices != null)
            {
                for (int i = 0; i < vertices.Length; i++)
                {
                    vertices[i].dispose();
                }
            }

            vertices = new TgcBox[points.Length];
            for (int i = 0; i < vertices.Length; i++)
            {
                vertices[i] = TgcBox.fromSize(points[i], new Vector3(1, 1, 1), Color.White);
            }
        }
Ejemplo n.º 24
0
        public override void Init()
        {
            //Cargar modelo
            var loader = new TgcSceneLoader();
            var scene  =
                loader.loadSceneFromFile(MediaDir +
                                         "MeshCreator\\Meshes\\Vehiculos\\StarWars-ATST\\StarWars-ATST-TgcScene.xml");

            mesh = scene.Meshes[0];

            //Computar OBB a partir del AABB del mesh. Inicialmente genera el mismo volumen que el AABB, pero luego te permite rotarlo (cosa que el AABB no puede)
            obb = TgcObb.computeFromAABB(mesh.BoundingBox);

            //Otra alternativa es computar OBB a partir de sus vertices. Esto genera un OBB lo mas apretado posible pero es una operacion costosa
            //obb = TgcObb.computeFromPoints(mesh.getVertexPositions());

            //Alejar camara rotacional segun tamaño del BoundingBox del objeto
            Camara = new TgcRotationalCamera(mesh.BoundingBox.calculateBoxCenter(),
                                             mesh.BoundingBox.calculateBoxRadius() * 2);

            //Modifier para poder rotar y mover el mesh
            Modifiers.addFloat("rotation", 0, 360, 0);
            Modifiers.addVertex3f("position", new Vector3(0, 0, 0), new Vector3(50, 50, 50), new Vector3(0, 0, 0));
        }
        public override void Init()
        {
            //Cuerpo principal que se controla con el teclado
            box = TgcBox.fromSize(new Vector3(0, 10, 0), new Vector3(10, 10, 10), Color.Blue);

            //triangulo
            triangle    = new CustomVertex.PositionColored[3];
            triangle[0] = new CustomVertex.PositionColored(-100, 0, 0, Color.Red.ToArgb());
            triangle[1] = new CustomVertex.PositionColored(0, 0, 50, Color.Green.ToArgb());
            triangle[2] = new CustomVertex.PositionColored(0, 100, 0, Color.Blue.ToArgb());
            triagleAABB =
                TgcBoundingBox.computeFromPoints(new[]
                                                 { triangle[0].Position, triangle[1].Position, triangle[2].Position });

            //box2
            box2 = TgcBox.fromSize(new Vector3(-50, 10, -20), new Vector3(15, 15, 15), Color.Violet);

            //sphere
            sphere = new TgcBoundingSphere(new Vector3(30, 20, -20), 15);

            //OBB: computar OBB a partir del AABB del mesh.
            var loader  = new TgcSceneLoader();
            var meshObb =
                loader.loadSceneFromFile(MediaDir +
                                         "MeshCreator\\Meshes\\Vehiculos\\StarWars-ATST\\StarWars-ATST-TgcScene.xml")
                .Meshes[0];

            obb = TgcObb.computeFromAABB(meshObb.BoundingBox);
            meshObb.dispose();
            obb.move(new Vector3(100, 0, 30));
            obb.setRotation(new Vector3(0, FastMath.PI / 4, 0));

            //Configurar camara en Tercer Persona
            camaraInterna = new TgcThirdPersonCamera(box.Position, 30, -75);
            Camara        = camaraInterna;
        }
 public ObbTranslatedUnRotatedCollider(TgcObb obb, Vector3 translation)
     : base(obb, translation)
 {
 }
Ejemplo n.º 27
0
 private void init()
 {
     foreach (TgcMesh mesh in escena)
     {
         obb = TgcObb.computeFromAABB(mesh.BoundingBox);
         if (TgcCollisionUtils.testObbAABB(obb, caja1.BoundingBox))
         {
             listaCaja1.Add(mesh);
         }
         if (TgcCollisionUtils.testObbAABB(obb, caja2.BoundingBox))
         {
             listaCaja2.Add(mesh);
         }
         if (TgcCollisionUtils.testObbAABB(obb, caja2.BoundingBox))
         {
             listaCaja2.Add(mesh);
         }
         if (TgcCollisionUtils.testObbAABB(obb, caja3.BoundingBox))
         {
             listaCaja3.Add(mesh);
         }
         if (TgcCollisionUtils.testObbAABB(obb, caja4.BoundingBox))
         {
             listaCaja4.Add(mesh);
         }
         if (TgcCollisionUtils.testObbAABB(obb, caja5.BoundingBox))
         {
             listaCaja5.Add(mesh);
         }
         if (TgcCollisionUtils.testObbAABB(obb, caja6.BoundingBox))
         {
             listaCaja6.Add(mesh);
         }
         if (TgcCollisionUtils.testObbAABB(obb, caja7.BoundingBox))
         {
             listaCaja7.Add(mesh);
         }
         if (TgcCollisionUtils.testObbAABB(obb, caja8.BoundingBox))
         {
             listaCaja8.Add(mesh);
         }
         if (TgcCollisionUtils.testObbAABB(obb, caja9.BoundingBox))
         {
             listaCaja9.Add(mesh);
         }
         if (TgcCollisionUtils.testObbAABB(obb, caja10.BoundingBox))
         {
             listaCaja10.Add(mesh);
         }
         if (TgcCollisionUtils.testObbAABB(obb, caja11.BoundingBox))
         {
             listaCaja11.Add(mesh);
         }
         if (TgcCollisionUtils.testObbAABB(obb, caja12.BoundingBox))
         {
             listaCaja12.Add(mesh);
         }
         if (TgcCollisionUtils.testObbAABB(obb, caja13.BoundingBox))
         {
             listaCaja13.Add(mesh);
         }
         if (TgcCollisionUtils.testObbAABB(obb, caja14.BoundingBox))
         {
             listaCaja14.Add(mesh);
         }
     }
 }
Ejemplo n.º 28
0
        public void render(float elapsedTime)
        {
            //moverse y rotar son variables que me indican a qué velocidad se moverá o rotará el mesh respectivamente.
            //Se inicializan en 0, porque por defecto está quieto.

            float moverse = 0f;
            float rotar   = 0f;

            habilitarDecremento = true;

            GuiController.Instance.UserVars.setValue("Velocidad", Math.Abs(auto.velocidadActual));
            GuiController.Instance.UserVars.setValue("Vida", escalaVida.X);
            GuiController.Instance.UserVars.setValue("AngCol", Geometry.RadianToDegree(anguloColision));
            GuiController.Instance.UserVars.setValue("AngRot", Geometry.RadianToDegree(anguloARotar));

            //aumento de la velocidad de rotacion al derrapar
            modificarVelocidadRotacion(auto);

            //Procesa las entradas del teclado.
            if (entrada.keyDown(Key.Q))
            {
                finDeJuego = true;
                salirConQ  = true;
            }

            if (entrada.keyDown(Key.S))
            {
                moverse = auto.irParaAtras(elapsedTime);
            }
            if (entrada.keyDown(Key.W))
            {
                moverse = auto.irParaAdelante(elapsedTime);
            }
            if (entrada.keyDown(Key.A) && (auto.velocidadActual > 0.5f || auto.velocidadActual < -0.5f)) //izquierda
            {
                rotar = -auto.velocidadRotacion;
            }
            if (entrada.keyDown(Key.D) && (auto.velocidadActual > 0.5f || auto.velocidadActual < -0.5f)) //derecha
            {
                rotar = auto.velocidadRotacion;
            }
            if (entrada.keyPressed(Key.M))
            {
                musica.muteUnmute();
                auto.mutearSonido();
            }
            if (entrada.keyPressed(Key.R)) //boton de reset, el mesh vuelve a la posicion de inicio y restaura todos sus parametros
            {
                auto.reiniciar();
                auto.mesh.move(new Vector3(0, 0, -3100));
                auto.mesh.rotateY(-1.57f);
                EjemploAlumno.instance.activar_efecto = false;
                nivel.reiniciar();
                this.reiniciar();
                GuiController.Instance.ThirdPersonCamera.resetValues();
                GuiController.Instance.ThirdPersonCamera.rotateY(-1.57f);
            }
            if (entrada.keyPressed(Key.B)) //Modo debug para visualizar BoundingBoxes entre otras cosas que nos sirvan a nosotros
            {
                Shared.debugMode = !Shared.debugMode;
            }
            if (entrada.keyPressed(Key.I))
            {
                modoDios = !modoDios;
            }

            //Frenado por inercia
            if (!entrada.keyDown(Key.W) && !entrada.keyDown(Key.S) && auto.velocidadActual != 0)
            {
                moverse = auto.frenarPorInercia(elapsedTime);
            }
            if (moverse > auto.velocidadMaxima)
            {
                auto.velocidadActual = auto.velocidadMaxima;
            }
            if (moverse < (-auto.velocidadMaxima))
            {
                auto.velocidadActual = -auto.velocidadMaxima;
            }

            int   sentidoRotacion = 0; //sentido de rotacion del reajuste de camara
            float rotCamara       = GuiController.Instance.ThirdPersonCamera.RotationY;
            float rotAuto         = auto.mesh.Rotation.Y;
            float deltaRotacion   = rotAuto - rotCamara;
            float dif             = FastMath.Abs(Geometry.RadianToDegree(deltaRotacion));
            float rapidez         = 5f; //aceleracion de reajuste de camara

            if (rotar != 0)
            {
                habilitarDecremento = false;
                habilitarContador   = true;
            }
            if (dif < 40)
            {
                if (dif < 30)
                {
                    if (dif < 20)
                    {
                        rapidez = 0.8f;
                    }
                    else
                    {
                        rapidez = 2f;
                    }
                }
                else
                {
                    rapidez = 3f;
                }
            }

            if (habilitarContador)
            {
                pasaronSegundos += elapsedTime;
            }

            if (deltaRotacion < 0)
            {
                sentidoRotacion = -1;
            }
            else
            {
                sentidoRotacion = 1;
            }

            if (deltaRotacion != 0 && pasaronSegundos > 0.5f)
            {
                ajustar           = true;
                pasaronSegundos   = 0f;
                habilitarContador = false;
            }


            float rotAngle = Geometry.DegreeToRadian(rotar * elapsedTime);

            if (ajustar)
            {
                GuiController.Instance.ThirdPersonCamera.rotateY(sentidoRotacion * rapidez * elapsedTime);
            }

            if (deltaRotacion < 0)
            {
                sentidoRotacion = -1;
            }
            else
            {
                sentidoRotacion = 1;
            }
            incrementarTiempo(this, elapsedTime, habilitarDecremento);
            auto.mesh.rotateY(rotAngle);
            auto.obb.rotate(new Vector3(0, rotAngle, 0));
            if (FastMath.Abs(Geometry.RadianToDegree(deltaRotacion)) % 360 < 3)
            {
                GuiController.Instance.ThirdPersonCamera.RotationY = rotAuto;
                ajustar = false;
            }


            if (habilitarDecremento)
            {
                incrementarTiempo(this, elapsedTime, habilitarDecremento);
            }

            if (moverse != 0 || auto.velocidadActual != 0) //Si hubo movimiento
            {
                Vector3 lastPos = auto.mesh.Position;
                auto.mesh.moveOrientedY(moverse * elapsedTime);
                Vector3 position = auto.mesh.Position;
                Vector3 posDiff  = position - lastPos;
                auto.obb.move(posDiff);
                Vector3 direccion = new Vector3(FastMath.Sin(auto.mesh.Rotation.Y) * moverse, 0, FastMath.Cos(auto.mesh.Rotation.Y) * moverse);
                auto.direccion.PEnd = auto.obb.Center + Vector3.Multiply(direccion, 50f);

                //Detectar colisiones de BoundingBox utilizando herramienta TgcCollisionUtils
                bool      collide = false;
                Vector3[] cornersAuto;
                Vector3[] cornersObstaculo;
                foreach (ObstaculoRigido obstaculo in nivel.obstaculos)
                {
                    if (Colisiones.testObbObb2(auto.obb, obstaculo.obb)) //chequeo obstáculo por obstáculo si está chocando con auto
                    {
                        collide              = true;
                        obstaculoChocado     = obstaculo;
                        Shared.mostrarChispa = true;
                        if (FastMath.Abs(auto.velocidadActual) > 800)
                        {
                            auto.reproducirSonidoChoque(FastMath.Abs(auto.velocidadActual));
                            auto.deformarMesh(obstaculo.obb, FastMath.Abs(auto.velocidadActual));
                        }
                        if (FastMath.Abs(auto.velocidadActual) > 800 && !modoDios)
                        {
                            escalaVida.X -= 0.00003f * Math.Abs(auto.velocidadActual) * escalaInicial.X;
                            if (escalaVida.X > 0.03f)
                            {
                                vida.setEscala(new Vector2(escalaVida.X, escalaVida.Y));
                            }
                            else
                            {
                                finDeJuego = true;
                                muerte     = true;
                            }
                        }
                        break;
                    }
                }
                //Si hubo colision, restaurar la posicion anterior (sino sigo de largo)
                if (collide)
                {
                    auto.mesh.Position = lastPos;
                    auto.obb.updateValues();
                    moverse = auto.chocar(elapsedTime);

                    if (FastMath.Abs(auto.velocidadActual) > 0)
                    {
                        cornersAuto      = CalculosVectores.computeCorners(auto);
                        cornersObstaculo = CalculosVectores.computeCorners(obstaculoChocado);
                        List <Plane> carasDelObstaculo = CalculosVectores.generarCaras(cornersObstaculo);
                        Vector3      NormalAuto        = direccion;
                        caraChocada = CalculosVectores.detectarCaraChocada(carasDelObstaculo, auto.puntoChoque);
                        Vector3 NormalObstaculo = new Vector3(caraChocada.A, caraChocada.B, caraChocada.C);
                        GuiController.Instance.UserVars.setValue("NormalObstaculoX", NormalObstaculo.X);
                        GuiController.Instance.UserVars.setValue("NormalObstaculoZ", NormalObstaculo.Z);

                        float desplazamientoInfinitesimal = 5f;
                        float constanteDesvio             = 1.3f;
                        //Calculo el angulo entre ambos vectores
                        anguloColision = CalculosVectores.calcularAnguloEntreVectoresNormalizados(NormalAuto, NormalObstaculo);//Angulo entre ambos vectores
                        //rota mesh
                        if (FastMath.Abs(auto.velocidadActual) > 800)
                        {
                            if (Geometry.RadianToDegree(anguloColision) < 25) //dado un cierto umbral, el coche rebota sin cambiar su direccion
                            {
                                auto.velocidadActual = -auto.velocidadActual;
                            }
                            else //el coche choca y cambia su direccion
                            {
                                if (NormalObstaculo.Z > 0 && direccion.X > 0 && direccion.Z > 0)
                                {
                                    anguloARotar = constanteDesvio * (Geometry.DegreeToRadian(90) - anguloColision);
                                    auto.mesh.move(new Vector3(0, 0, -10));
                                    colorDeColision = Color.Red;
                                }

                                if (NormalObstaculo.X > 0 && direccion.X > 0 && direccion.Z > 0)
                                {
                                    anguloARotar = -constanteDesvio * (Geometry.DegreeToRadian(90) - anguloColision);
                                    auto.mesh.move(new Vector3(-5, 0, 0));
                                    colorDeColision = Color.Salmon;
                                }

                                if (NormalObstaculo.X > 0 && direccion.X > 0 && direccion.Z < 0)
                                {
                                    anguloARotar    = constanteDesvio * (Geometry.DegreeToRadian(90) - anguloColision);
                                    colorDeColision = Color.Blue;
                                    auto.mesh.move(new Vector3(-desplazamientoInfinitesimal, 0, 0));
                                }

                                if (NormalObstaculo.Z < 0 && direccion.X > 0 && direccion.Z < 0)
                                {
                                    anguloARotar = -constanteDesvio * (Geometry.DegreeToRadian(90) - anguloColision);
                                    auto.mesh.move(new Vector3(0, 0, desplazamientoInfinitesimal));
                                    colorDeColision = Color.Green;
                                }

                                if (NormalObstaculo.Z < 0 && direccion.X < 0 && direccion.Z < 0)
                                {
                                    anguloARotar = constanteDesvio * (Geometry.DegreeToRadian(90) - anguloColision);
                                    auto.mesh.move(new Vector3(0, 0, desplazamientoInfinitesimal));
                                    colorDeColision = Color.Pink;
                                }


                                if (NormalObstaculo.X < 0 && direccion.X < 0 && direccion.Z < 0)
                                {
                                    anguloARotar = -constanteDesvio * (Geometry.DegreeToRadian(90) - anguloColision);
                                    auto.mesh.move(new Vector3(desplazamientoInfinitesimal, 0, 0));
                                    colorDeColision = Color.Silver;
                                }

                                if (NormalObstaculo.X < 0 && direccion.X < 0 && direccion.Z > 0)
                                {
                                    anguloARotar = constanteDesvio * (Geometry.DegreeToRadian(90) - anguloColision);
                                    auto.mesh.move(new Vector3(desplazamientoInfinitesimal, 0, 0));
                                    colorDeColision = Color.Aquamarine;
                                }

                                if (NormalObstaculo.Z > 0 && direccion.X < 0 && direccion.Z > 0)
                                {
                                    anguloARotar = -constanteDesvio * (Geometry.DegreeToRadian(90) - anguloColision);
                                    auto.mesh.move(new Vector3(0, 0, -desplazamientoInfinitesimal));
                                    colorDeColision = Color.Yellow;
                                }

                                auto.mesh.rotateY(anguloARotar);
                            }
                        }
                    }
                }

                foreach (Recursos recurso in nivel.recursos)
                {
                    TgcCollisionUtils.BoxBoxResult result = TgcCollisionUtils.classifyBoxBox(auto.mesh.BoundingBox, recurso.modelo.BoundingBox);
                    if (result == TgcCollisionUtils.BoxBoxResult.Adentro || result == TgcCollisionUtils.BoxBoxResult.Atravesando)
                    {
                        nivel.recursos.Remove(recurso); //Saca el recurso de la lista para que no se renderice más
                        float puntos = Convert.ToSingle(this.puntos.Text) + 100f;
                        this.puntos.Text = Convert.ToString(puntos);
                        break;
                    }
                }
                //Chequeo si el auto agarro el checkpoint actual
                if (Colisiones.testObbObb2(auto.obb, nivel.checkpointActual.obb))
                {
                    if (nivel.checkpointsRestantes.Text != "1")
                    {
                        nivel.checkpoints.Remove(nivel.checkpointActual);       //Saca el checkpoint de la lista para que no se renderice más
                        int restantes = (Convert.ToInt16(nivel.checkpointsRestantes.Text) - 1);
                        nivel.checkpointsRestantes.Text = restantes.ToString(); //Le resto uno a los restantes
                        this.tiempoRestante.Text        = (Convert.ToSingle(this.tiempoRestante.Text) + 10f).ToString();
                        nivel.checkpointActual          = nivel.checkpoints.ElementAt(0);
                    }
                    else
                    {
                        finDeJuego = true;
                    }
                }

                //Efecto blur
                if (FastMath.Abs(auto.velocidadActual) > (auto.velocidadMaxima * 0.5555))
                {
                    EjemploAlumno.instance.activar_efecto = true;
                    EjemploAlumno.instance.blur_intensity = 0.003f * (float)Math.Round(FastMath.Abs(auto.velocidadActual) / (auto.velocidadMaxima), 5);
                }
                else
                {
                    EjemploAlumno.instance.activar_efecto = false;
                }
            }
            GuiController.Instance.ThirdPersonCamera.Target = auto.mesh.Position;

            //actualizo cam
            Vector2 vectorCam = (Vector2)GuiController.Instance.Modifiers["AlturaCamara"];

            GuiController.Instance.ThirdPersonCamera.setCamera(auto.mesh.Position, vectorCam.X, vectorCam.Y);

            float tope             = 1f;
            float constanteDerrape = ((tiempoTrans / 2) < tope) ? (tiempoTrans / 2) : tope;
            float proporcion       = FastMath.Abs(auto.velocidadActual / auto.velocidadMaxima);

            if (sentidoAnterior != sentidoRotacion && tiempoTrans != 0)
            {
                incrementarTiempo(this, elapsedTime * 5, true);
            }
            if (tiempoTrans == 0)
            {
                sentidoAnterior = sentidoRotacion;
            }

            auto.mesh.rotateY(constanteDerrape * sentidoAnterior * proporcion);

            auto.render();

            auto.obb = TgcObb.computeFromAABB(auto.mesh.BoundingBox);
            auto.obb.setRotation(auto.mesh.Rotation);
            auto.obb.setRenderColor(colorDeColision);

            auto.mesh.rotateY(-constanteDerrape * sentidoAnterior * proporcion);

            //dibuja el nivel
            nivel.render(elapsedTime);

            //AJUSTE DE CAMARA SEGUN COLISION
            ajustarCamaraSegunColision(auto, nivel.obstaculos);

            //Dibujo checkpoints restantes
            nivel.checkpointsRestantes.render();

            //Dibujo el puntaje del juego
            this.puntos.render();

            //CUENTA REGRESIVA
            if (this.tiempoRestante.Text == "1")
            {
                uno.render();
            }
            if (this.tiempoRestante.Text == "2")
            {
                dos.render();
            }

            if (this.tiempoRestante.Text == "3")
            {
                tres.render();
            }

            //Actualizo y dibujo el relops
            if ((DateTime.Now.Subtract(this.horaInicio).TotalSeconds) > segundosAuxiliares && !modoDios)
            {
                this.tiempoRestante.Text = (Convert.ToDouble(tiempoRestante.Text) - 1).ToString();
                if (this.tiempoRestante.Text == "0") //Si se acaba el tiempo, me muestra el game over y reseetea todo
                {
                    finDeJuego = true;
                    muerte     = true;
                }
                segundosAuxiliares++;
            }
            this.tiempoRestante.render();

            //Si se le acabo el tiempo o la vida, o apretó "Q"
            if (finDeJuego)
            {
                //corta la música al salir
                TgcMp3Player player = GuiController.Instance.Mp3Player;
                player.closeFile();
                GuiController.Instance.UserVars.clearVars();
                //saca el blur
                EjemploAlumno.instance.activar_efecto = false;
                //reinicia los valores de las cosas del juego
                auto.reiniciar();
                nivel.reiniciar();
                this.reiniciar();
                //reinicia la camara
                GuiController.Instance.ThirdPersonCamera.resetValues();
                if (muerte)
                {
                    EjemploAlu.setPantalla(EjemploAlu.getPantalla(1));
                }
                else if (salirConQ)
                {
                    EjemploAlumno.getInstance().setPantalla(new PantallaInicio());
                }
                else
                {
                    EjemploAlu.setPantalla(EjemploAlu.getPantalla(2));
                }
            }

            if (comienzoNivel)
            {
                if (DateTime.Now.Subtract(this.horaInicio).TotalSeconds < 3)
                {
                    if (auto.nombre == "Luigi")
                    {
                        misionLuigi.render();
                    }
                    else
                    {
                        misionMario.render();
                    }
                }
                else
                {
                    comienzoNivel = false;
                }
            }
            else
            {
                //Dibujo barrita
                if (auto.nombre == "Luigi")
                {
                    barra2.render();
                }
                else
                {
                    barra.render();
                }
                vida.render();
            }
            //renderizo utilidades del debugMode
            if (Shared.debugMode)
            {
                Vector2 vectorModifier = (Vector2)GuiController.Instance.Modifiers["PosicionFlechaDebug"];
                Vector3 vectorPosicion = new Vector3(vectorModifier.X, 10, vectorModifier.Y);
                debugArrow.PStart = vectorPosicion + new Vector3(0, 400f, 0);
                debugArrow.PEnd   = vectorPosicion;
                debugArrow.updateValues();
                debugArrow.render();

                //renderizo normal al plano chocado
                if (obstaculoChocado != null)
                {
                    collisionNormalArrow.PStart = obstaculoChocado.obb.Center;
                    collisionNormalArrow.PEnd   = obstaculoChocado.obb.Center + Vector3.Multiply(new Vector3(caraChocada.A, caraChocada.B, caraChocada.C), 500f);
                    collisionNormalArrow.updateValues();
                    collisionNormalArrow.render();
                }
            }
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Testear si hay olision entre dos OBB
 /// </summary>
 /// <param name="a">Primer OBB</param>
 /// <param name="b">Segundo OBB</param>
 /// <returns>True si hay colision</returns>
 public static bool testObbObb2(TgcObb a, TgcObb b)
 {
     return(Colisiones.testObbObb2(a.toStruct(), b.toStruct()));
 }
Ejemplo n.º 30
0
 public ObstaculoRigido(TgcMesh _mesh)
 {
     this.obb  = TgcObb.computeFromAABB(_mesh.BoundingBox);
     this.mesh = _mesh;
 }