Example #1
0
        public override void render(float elapsedTime)
        {
            motionBlurFlag = (bool)GuiController.Instance.Modifiers["motionBlurFlag"];
            TgcTexture texture = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "TheC#\\Pista\\pistaCarreras.png");

            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;


            //pantalla De Inicio
            if (flagInicio == 0)
            {
                //Actualizar valores cargados en modifiers

                /*sprite.Position = (Vector2)GuiController.Instance.Modifiers["position"];
                 * sprite.Scaling = (Vector2)GuiController.Instance.Modifiers["scaling"];
                 * sprite.Rotation = FastMath.ToRad((float)GuiController.Instance.Modifiers["rotation"]);
                 */
                //Iniciar dibujado de todos los Sprites de la escena (en este caso es solo uno)
                GuiController.Instance.Drawer2D.beginDrawSprite();
                sprite.render();
                //Finalizar el dibujado de Sprites
                GuiController.Instance.Drawer2D.endDrawSprite();
                flagInicio = jugador.verSiAprietaSpace();
                textIngreseTeclaSombra.render();
                textIngreseTecla.render();
                musica.verSiCambioMP3();
            }
            else
            {
                //Para contar el tiempo desde que preciona la barra espaciadora y comienza el juego
                if (primerRenderDelJuegoAndando == true)
                {
                    this.horaInicio             = DateTime.Now;
                    primerRenderDelJuegoAndando = false;
                }
                //Todo lo referente a lo que debe hacer el IA
                autoIA.elapsedTime = elapsedTime;
                autoIA.establecerVelocidadMáximaEn((float)GuiController.Instance.Modifiers["velocidadMaxima"] * 1.02f);

                if (colision.getTiempoQueChoco() == 0)
                {
                    jugadorIA.jugar(trayectoDeIA[0].Center, meshAutoIA.Position);
                }

                meshAutoIA.Rotation = new Vector3(0f, autoIA.rotacion, 0f);
                jugadorIA.setRotacion(meshAutoIA.Rotation);

                meshAutoIA.moveOrientedY(-autoIA.velocidad * elapsedTime);
                //Fin movimiento de auto IA

                //Le paso el elapsed time al auto porque sus metodos no deben depender de los FPS
                auto.elapsedTime = elapsedTime;

                //Varío la velocidad Máxima del vehículo con el modifier "velocidadMáxima"
                auto.establecerVelocidadMáximaEn((float)GuiController.Instance.Modifiers["velocidadMaxima"]);

                //El jugador envia mensajes al auto dependiendo de que tecla presiono
                //Se pone un tiempo para que luego de chocar 2 autos, estos no puedan ingresar movimiento (sólo se mueve por inercia)
                if (colision.getTiempoQueChoco() == 0)
                {
                    jugador.jugar(cantidadDeNitro);
                }
                else
                {
                    colision.setTiempoQueChoco(colision.getTiempoQueChoco() - (8 * elapsedTime));
                    if (colision.getTiempoQueChoco() < 0)
                    {
                        colision.setTiempoQueChoco(0);
                    }
                }

                //Transfiero la rotacion del auto abstracto al mesh, y su obb
                autoMesh.Rotation = new Vector3(0f, auto.rotacion, 0f);
                oBBAuto.Center    = autoMesh.Position;
                oBBAuto.setRotation(autoMesh.Rotation);
                meshAutoIA.Rotation = new Vector3(0f, autoIA.rotacion, 0f);
                oBBAutoIa.Center    = meshAutoIA.Position;
                oBBAutoIa.setRotation(meshAutoIA.Rotation);


                //Calculo de giro de la rueda
                rotacionVertical -= auto.velocidad * elapsedTime / 60;

                //Calculo el movimiento del mesh dependiendo de la velocidad del auto
                autoMesh.moveOrientedY(-auto.velocidad * elapsedTime);
                //Detección de colisiones
                //Hubo colisión con un objeto. Guardar resultado y abortar loop.



                //Si hubo alguna colisión, hacer esto:
                if (huboColision(oBBAuto))
                {
                    autoMesh.moveOrientedY(20 * auto.velocidad * elapsedTime); //Lo hago "como que rebote un poco" para no seguir colisionando
                    auto.velocidad = -(auto.velocidad * 0.3f);                 //Lo hago ir atrás un tercio de velocidad de choque
                }
                if (huboColision(oBBAutoIa))
                {
                    meshAutoIA.moveOrientedY(20 * autoIA.velocidad * elapsedTime); //Lo hago "como que rebote un poco" para no seguir colisionando
                    autoIA.velocidad = -(autoIA.velocidad * 0.3f);                 //Lo hago ir atrás un tercio de velocidad de choque
                }

                //Colisión entre los autos
                for (int i = 0; i < 4; i++)
                {
                    float ro, alfa_rueda;
                    float posicion_xA1;
                    float posicion_yA1;
                    float posicion_xA2;
                    float posicion_yA2;

                    ro = FastMath.Sqrt(dx[i] * dxAColision[i] + dyAColision[i] * dyAColision[i]);

                    alfa_rueda = FastMath.Asin(dxAColision[i] / ro);
                    if (i == 0 || i == 2)
                    {
                        alfa_rueda += FastMath.PI;
                    }
                    posicion_xA1 = FastMath.Sin(alfa_rueda + auto.rotacion) * ro;
                    posicion_yA1 = FastMath.Cos(alfa_rueda + auto.rotacion) * ro;

                    posicion_xA2 = FastMath.Sin(alfa_rueda + autoIA.rotacion) * ro;
                    posicion_yA2 = FastMath.Cos(alfa_rueda + autoIA.rotacion) * ro;

                    obbsAuto[i].Position = (new Vector3(posicion_xA1, 15.5f, posicion_yA1) + autoMesh.Position);

                    obbsOtroAuto[i].Position = (new Vector3(posicion_xA2, 15.5f, posicion_yA2) + meshAutoIA.Position);
                }

                colision.colisionEntreAutos(obbsAuto, obbsOtroAuto, jugador, auto, autoIA, autoMesh, meshAutoIA, elapsedTime);

                //Cosas sobre derrape
                int direcGiroDerrape = 0;

                if (auto.velocidad > 1500 && (jugador.estaGirandoDerecha() || jugador.estaGirandoIzquierda()))
                {
                    if (jugador.estaGirandoIzquierda())
                    {
                        direcGiroDerrape = -1;
                    }
                    else if (jugador.estaGirandoDerecha())
                    {
                        direcGiroDerrape = 1;
                    }

                    autoMesh.Rotation = new Vector3(0f, auto.rotacion + (direcGiroDerrape * anguloDerrape), 0f);
                    oBBAuto.setRotation(new Vector3(autoMesh.Rotation.X, autoMesh.Rotation.Y + (direcGiroDerrape * anguloDerrape / 2), autoMesh.Rotation.Z));


                    if (anguloDerrape <= anguloMaximoDeDerrape)
                    {
                        anguloDerrape += velocidadDeDerrape * elapsedTime;
                    }
                }
                else
                {
                    direcGiroDerrape = 0;
                    anguloDerrape    = 0;
                }
                //Fin derrape

                //Posiciono las ruedas
                for (int i = 0; i < 4; i++)
                {
                    float ro, alfa_rueda;
                    float posicion_x;
                    float posicion_y;
                    ro = FastMath.Sqrt(dx[i] * dx[i] + dy[i] * dy[i]);

                    alfa_rueda = FastMath.Asin(dx[i] / ro);
                    if (i == 0 || i == 2)
                    {
                        alfa_rueda += FastMath.PI;
                    }
                    posicion_x = FastMath.Sin(alfa_rueda + auto.rotacion + (anguloDerrape * direcGiroDerrape)) * ro;
                    posicion_y = FastMath.Cos(alfa_rueda + auto.rotacion + (anguloDerrape * direcGiroDerrape)) * ro;

                    ruedas[i].Position = (new Vector3(posicion_x, 15.5f, posicion_y) + autoMesh.Position);
                    //Si no aprieta para los costados, dejo la rueda derecha (por ahora, esto se puede modificar)
                    if (input.keyDown(Key.Left) || input.keyDown(Key.A) || input.keyDown(Key.Right) || input.keyDown(Key.D))
                    {
                        ruedas[i].Rotation = new Vector3(rotacionVertical, auto.rotacion + auto.rotarRueda(i) + (anguloDerrape * direcGiroDerrape), 0f);
                    }
                    else
                    {
                        ruedas[i].Rotation = new Vector3(rotacionVertical, auto.rotacion + (anguloDerrape * direcGiroDerrape), 0f);
                    }
                }

                //comienzo humo
                float rohumo, alfa_humo;
                float posicion_xhumo;
                float posicion_yhumo;
                rohumo = FastMath.Sqrt(-19f * -19f + 126f * 126f);

                alfa_humo      = FastMath.Asin(-19f / rohumo);
                posicion_xhumo = FastMath.Sin(alfa_humo + auto.rotacion + (anguloDerrape * direcGiroDerrape)) * rohumo;
                posicion_yhumo = FastMath.Cos(alfa_humo + auto.rotacion + (anguloDerrape * direcGiroDerrape)) * rohumo;

                humo.Position = (new Vector3(posicion_xhumo, 15.5f, posicion_yhumo) + autoMesh.Position);
                //Si no aprieta para los costados, dejo la rueda derecha (por ahora, esto se puede modificar)
                if (input.keyDown(Key.Left) || input.keyDown(Key.A) || input.keyDown(Key.Right) || input.keyDown(Key.D))
                {
                    humo.Rotation = new Vector3(0f, auto.rotacion + (anguloDerrape * direcGiroDerrape), 0f);
                }
                else
                {
                    humo.Rotation = new Vector3(0f, auto.rotacion + (anguloDerrape * direcGiroDerrape), 0f);
                }
                //fin de humo
                fuego.Position = humo.Position;
                fuego.Rotation = humo.Rotation;
                //fin fuego

                cantidadDeNitro += 0.5f * elapsedTime;
                cantidadDeNitro  = FastMath.Min(cantidadDeNitro, 100f);
                if (auto.nitro)
                {
                    cantidadDeNitro -= 7 * elapsedTime;
                    cantidadDeNitro  = FastMath.Max(cantidadDeNitro, 0f);
                    if (cantidadDeNitro > 1)
                    {
                        humo.Enabled  = false;
                        fuego.Enabled = false;
                    }
                }
                else
                {
                    humo.Enabled  = false;
                    fuego.Enabled = false;
                }
                tiempoHumo   += elapsedTime;
                humo.UVOffset = new Vector2(0.9f, tiempoHumo);
                humo.updateValues();
                fuego.UVOffset = new Vector2(0.9f, tiempoHumo);
                fuego.updateValues();

                if (tiempoHumo > 50f)
                {
                    tiempoHumo = 0f;
                }
                autoMeshPrevX = autoMesh.Position.X;
                autoMeshPrevZ = autoMesh.Position.Z;

                //Lineas de Frenado
                if (jugador.estaFrenandoDeMano())
                {
                    lineaDeFrenado[0].addTrack(new Vector3(ruedaDerechaDelanteraMesh.Position.X, 0, ruedaDerechaDelanteraMesh.Position.Z));
                    lineaDeFrenado[1].addTrack(new Vector3(ruedaDerechaTraseraMesh.Position.X, 0, ruedaDerechaTraseraMesh.Position.Z));
                    lineaDeFrenado[2].addTrack(new Vector3(ruedaIzquierdaDelanteraMesh.Position.X, 0, ruedaIzquierdaDelanteraMesh.Position.Z));
                    lineaDeFrenado[3].addTrack(new Vector3(ruedaIzquierdaTraseraMesh.Position.X, 0, ruedaIzquierdaTraseraMesh.Position.Z));
                }
                if (jugador.dejoDeFrenarDeMano())
                {
                    for (int i = 0; i < lineaDeFrenado.Length; i++)
                    {
                        lineaDeFrenado[i].endTrack();
                    }
                }

                for (int i = 0; i < lineaDeFrenado.Length; i++)
                {
                    lineaDeFrenado[i].render();
                    lineaDeFrenado[i].pasoDelTiempo(elapsedTime);
                }

                //Dibujo el reflejo de la luz en el auto
                reflejo.Render();

                //////Camara///////

                if (jugador.estaMirandoHaciaAtras())
                {
                    GuiController.Instance.ThirdPersonCamera.setCamera(autoMesh.Position, 200, -500);
                    GuiController.Instance.ThirdPersonCamera.Target    = autoMesh.Position;
                    GuiController.Instance.ThirdPersonCamera.RotationY = auto.rotacion;
                }
                else
                {
                    coheficienteCamara = jugador.verSiCambiaCamara();
                    GuiController.Instance.ThirdPersonCamera.setCamera(autoMesh.Position, 100 + (coheficienteCamara), 900 - (coheficienteCamara) * 4);
                    GuiController.Instance.ThirdPersonCamera.Target    = autoMesh.Position;
                    GuiController.Instance.ThirdPersonCamera.RotationY = auto.rotacion;
                }

                //La camara no rota exactamente a la par del auto, hay un pequeño retraso
                //GuiController.Instance.ThirdPersonCamera.RotationY += 5 * (auto.rotacion - prevCameraRotation) * elapsedTime;
                //Ajusto la camara a menos de 360 porque voy a necesitar hacer calculos entre angulos
                while (prevCameraRotation > 360)
                {
                    prevCameraRotation -= 360;
                }
                prevCameraRotation = GuiController.Instance.ThirdPersonCamera.RotationY;

                ///////Musica/////////
                jugador.verSiModificaMusica(musica);

                //Dibujar objeto principal
                //Siempre primero hacer todos los cálculos de lógica e input y luego al final dibujar todo (ciclo update-render)
                foreach (TgcMesh mesh in scenePista.Meshes)
                {
                    mesh.Enabled = (TgcCollisionUtils.classifyFrustumAABB(GuiController.Instance.Frustum, mesh.BoundingBox) != TgcCollisionUtils.FrustumResult.OUTSIDE);
                }
                if (motionBlurFlag)
                {
                    motionBlur.update(elapsedTime);
                    motionBlur.motionBlurRender(elapsedTime, HighResolutionTimer.Instance.FramesPerSecond, auto.velocidad, 0);
                }
                else
                {
                    foreach (TgcMesh mesh in scenePista.Meshes)
                    {
                        mesh.Technique = "DefaultTechnique";
                        mesh.render();
                    }
                }

                //Mostrar al auto IA
                meshAutoIA.render();

                //Muestro el punto siguiente
                trayecto[0].render();
                //mostrar el auto manejado por el humano
                autoMesh.render();

                for (int i = 0; i < 4; i++)
                {
                    ruedas[i].render();
                }

                humo.render();
                fuego.render();

                //Colision con puntos de control, tanto de persona como IA
                for (int i = 0; i < trayecto.Count; i++)
                {
                    //Pregunto si colisiona con un punto de control activado. Lo sé, feo.
                    if ((i == 0) && TgcCollisionUtils.testPointCylinder(oBBAuto.Position, trayecto[i].BoundingCylinder))
                    {
                        TgcCylinder cilindroModificado = new TgcCylinder(trayecto[i].Center, 130, 30);

                        if (contadorDeActivacionesDePuntosDeControl != (posicionesPuntosDeControl.Count * 3))
                        {
                            trayecto.RemoveAt(i);
                            trayecto.Add(cilindroModificado);
                            contadorDeActivacionesDePuntosDeControl++;
                            textPuntosDeControlAlcanzados.Text = "Puntos De Control Alcanzados = " + contadorDeActivacionesDePuntosDeControl.ToString();
                            textTiempo.Text = (Convert.ToDouble(textTiempo.Text) + 3).ToString();
                        }
                        else
                        {
                            gano             = true;
                            textGanaste.Text = "Ganaste y obtuviste un puntaje de  " + textTiempo.Text + " puntos";
                            textGanaste.render();
                            auto.estatico();
                            //Para el IA
                            autoIA.estatico();
                        }
                    }
                }
                for (int i = 0; i < trayectoDeIA.Count; i++)
                {
                    //Pregunto si colisiona con un punto de control activado
                    if ((i == 0) && TgcCollisionUtils.testPointCylinder(meshAutoIA.Position, trayectoDeIA[i].BoundingCylinder))
                    {
                        TgcCylinder cilindroModificado = new TgcCylinder(trayectoDeIA[i].Center, 130, 30);

                        if (contadorDeActivacionesDePuntosDeControlDeIA != (posicionesPuntosDeControlDeIA.Count * 3))
                        {
                            trayectoDeIA.RemoveAt(i);
                            trayectoDeIA.Add(cilindroModificado);
                            contadorDeActivacionesDePuntosDeControlDeIA++;
                        }
                        else
                        {
                            gano             = true;
                            textGanaste.Text = "Ganó la máquina :P  ";
                            textGanaste.render();
                            //Para el IA
                            autoIA.estatico();
                            auto.estatico();
                        }
                    }
                }

                textPosicionDelAutoActual.Text = autoMesh.Position.ToString();

                //Renderizar los tres textos

                textoVelocidad.mostrarVelocidad(auto.velocidad / 10).render(); //renderiza la velocidad

                textPuntosDeControlAlcanzados.render();
                textPosicionDelAutoActual.render();

                //Cosas del tiempo
                tiempo.incrementarTiempo(this, elapsedTime, (bool)GuiController.Instance.Modifiers["jugarConTiempo"]);

                //Actualizo y dibujo el relops
                if ((bool)GuiController.Instance.Modifiers["jugarConTiempo"])
                {
                    if ((DateTime.Now.Subtract(this.horaInicio).TotalSeconds) > segundosAuxiliares)
                    {
                        if (Convert.ToDouble(textTiempo.Text) == 0)
                        {
                            textPerdiste.Text = "Perdiste y lograste " + contadorDeActivacionesDePuntosDeControl.ToString() + " puntos de control";
                            textPerdiste.render();
                            auto.estatico();
                            //Para el IA
                            autoIA.estatico();
                        }
                        else if (gano == true)
                        {
                        }
                        else
                        {
                            this.textTiempo.Text = (Convert.ToDouble(textTiempo.Text) - 1).ToString();
                            segundosAuxiliares++;
                        }
                    }
                }
                emisorHumo.update(elapsedTime, GuiController.Instance.CurrentCamera.getLookAt(), auto.rotacion, autoMesh.Position, anguloDerrape, direcGiroDerrape, auto.nitro && (cantidadDeNitro > 1), auto.velocidad);
                emisorHumo.render(GuiController.Instance.CurrentCamera.getPosition());
                textTiempo.render();
                stringTiempo.render();
                contadorDeFrames++;

                hud.render(auto.velocidad, cantidadDeNitro);
            }//cierra el if de que no esta en pantalla inicio
            textFPS.Text = "            FPS: " + HighResolutionTimer.Instance.FramesPerSecond.ToString();
            textFPS.render();
        }