public void init(string mediaDir, string shaderDir, TgcCamera camara) { reproductorMp3.closeFile(); pathDeLaCancion = mediaDir + "Musica\\gameover.mp3"; reproductorMp3.FileName = pathDeLaCancion; volver = new Boton("Volver al Menú principal", 0f, 0.8f, () => { reproductorMp3.closeFile(); AdministradorDeEscenarios.getSingleton().agregarEscenario(new Menu(), camara); }); sprite = new Sprite(D3DDevice.Instance.Device); gameOver = TgcTexture.createTexture(D3DDevice.Instance.Device, mediaDir + "gameover.jpg"); reproductorMp3.play(true); }
public void init(string mediaDir, string shaderDir, TgcCamera camara) { pathDeLaCancion = mediaDir + "Musica\\MissionComplete.mp3"; reproductorMp3.FileName = pathDeLaCancion; reproductorMp3.play(true); volver = new Boton("Volver al Menú principal", 0f, 0.8f, () => { reproductorMp3.closeFile(); AdministradorDeEscenarios.getSingleton().agregarEscenario(new Menu(), camara); }); texto = new Boton("Felicidades, aprobaste 2 materias ¿Hasta dónde llegarás?", 0f, 0.7f, null); sprite = new Sprite(D3DDevice.Instance.Device); victory = TgcTexture.createTexture(D3DDevice.Instance.Device, mediaDir + "victory.jpg"); }
public void init(string mediaDir, string shaderDir, TgcCamera camara) { pathDeLaCancion = mediaDir + "Musica\\MissionComplete.mp3"; reproductorMp3.FileName = pathDeLaCancion; reproductorMp3.play(true); volver = new Boton("Cursar PdeP", 0f, 0.8f, () => { reproductorMp3.closeFile(); AdministradorDeEscenarios.getSingleton().agregarEscenario(new nivelPDP(), camara); }); texto = new Boton("Bien, te hiciste todos los ejercicios habidos y por haber ¿Seguimos?", 0f, 0.7f, null); sprite = new Sprite(D3DDevice.Instance.Device); victory = TgcTexture.createTexture(D3DDevice.Instance.Device, mediaDir + "missionPassed.png"); }
/// <summary> /// Cargar un nuevo MP3 si hubo una variacion /// </summary> private void loadMp3(string filePath) { if (currentFile == null || currentFile != filePath) { currentFile = filePath; //Cargar archivo mp3Player.closeFile(); mp3Player.FileName = currentFile; currentMusicText.Text = "Playing: " + new FileInfo(currentFile).Name; } }
///////////////////////////////////////////////////////////////////////// /// ////////////////////////////DISPOSE////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// public void dispose() { personajePrincipal.Dispose(); //Dispose del personaje. coleccionablesAdquiridos.Dispose(); foreach (TgcMesh mesh in scene.Meshes) { if (!coleccionablesAgarrados.Contains(mesh)) { mesh.Dispose(); } reproductorMp3.closeFile(); } }
public override void Update() { //Ver si cambio el MP3 var filePath = mp3FileModifier.Value; loadMp3(filePath); //Contro del reproductor por teclado var currentState = mp3Player.getStatus(); if (Input.keyPressed(Key.Y)) { if (currentState == TgcMp3Player.States.Open) { //Reproducir MP3 mp3Player.play(true); } if (currentState == TgcMp3Player.States.Stopped) { //Parar y reproducir MP3 mp3Player.closeFile(); mp3Player.play(true); } } else if (Input.keyPressed(Key.U)) { if (currentState == TgcMp3Player.States.Playing) { //Pausar el MP3 mp3Player.pause(); } } else if (Input.keyPressed(Key.I)) { if (currentState == TgcMp3Player.States.Paused) { //Resumir la ejecución del MP3 mp3Player.resume(); } } else if (Input.keyPressed(Key.O)) { if (currentState == TgcMp3Player.States.Playing) { //Parar el MP3 mp3Player.stop(); } } }
public void ReproducirWoah() { cancionPpal.pause(); woah.closeFile(); woah.play(false); cancionPpal.resume(); }
public override void Dispose() { moto.dispose(); foreach (TgcMesh caja in cajas) { caja.dispose(); } controladorIA.disposeOponentes(); skyBoxTron.dispose(); texto.Dispose(); textoModoDios.Dispose(); cajaConLuz.dispose(); efectoLuz.Dispose(); gestorPowerUps.dispose(); pisoPlane.dispose(); piso.dispose(); mp3Player.closeFile(); }
private void Player() { TgcMp3Player player = new TgcMp3Player(); //if ((bool)GuiController.Instance.Modifiers["Musica"]) { if (player.getStatus() == TgcMp3Player.States.Open) { //Reproducir MP3 //FIXME //player.play(true); } if (player.getStatus() == TgcMp3Player.States.Stopped) { //Parar y reproducir MP3 player.closeFile(); player.play(true); } } /*else * { * if (player.getStatus() == TgcMp3Player.States.Playing) * { * //Parar el MP3 * player.stop(); * } * }*/ }
public void Dispose(TgcMp3Player music) { if (music.FileName != null) { music.closeFile(); } }
public void Pozo() { CanJump = false; SetAnimation("Jump", false); woah.closeFile(); woah.FileName = Env.MediaDir + "\\Sound\\woah.mp3"; woah.play(false); }
public override void render(float elapsedTime) { Device d3dDevice = GuiController.Instance.D3dDevice; //Ver si cambio el MP3 string filePath = (string)GuiController.Instance.Modifiers["MP3-File"]; loadMp3(filePath); //Contro del reproductor por teclado TgcMp3Player player = GuiController.Instance.Mp3Player; TgcMp3Player.States currentState = player.getStatus(); if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.Y)) { if (currentState == TgcMp3Player.States.Open) { //Reproducir MP3 player.play(true); } if (currentState == TgcMp3Player.States.Stopped) { //Parar y reproducir MP3 player.closeFile(); player.play(true); } } else if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.U)) { if (currentState == TgcMp3Player.States.Playing) { //Pausar el MP3 player.pause(); } } else if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.I)) { if (currentState == TgcMp3Player.States.Paused) { //Resumir la ejecución del MP3 player.resume(); } } else if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.O)) { if (currentState == TgcMp3Player.States.Playing) { //Parar el MP3 player.stop(); } } //Render texto currentMusicText.render(); instruccionesText.render(); }
///////////////////////////////////////////////////////////////////////// ////////////////////////////////DISPOSE////////////////////////////////// ///////////////////////////////////////////////////////////////////////// public void dispose() { foreach (TgcMesh mesh in scene.Meshes) { if (!librosAgarrados.Contains(mesh)) { mesh.Dispose(); } } personajePrincipal.Dispose(); reproductorMp3.closeFile(); emisorDeParticulas1.dispose(); emisorDeParticulas2.dispose(); emisorDeParticulas3.dispose(); }
public override Escena Update(float ElapsedTime) { if (Input.keyDown(Microsoft.DirectX.DirectInput.Key.Space)) { mp3Gameover.closeFile(); return(CambiarEscena(new EscenaMenu(Camera, MediaDir, ShadersDir, DrawText, TimeBetweenUpdates, Input))); } return(this); }
/// <summary> /// Play un nuevo MP3 solo /// </summary> public void playMp3(string filePath) { mp3Player.stop(); mp3Player.closeFile(); loadMp3(filePath); mp3Player.play(false); }
public override void Update() { PreUpdate(); //movimientoCaja = TGCMatrix.Identity; //// Agrego a la lista de meshes colisionables tipo caja, todas las cosas del pedazo de escenario donde estoy contra las que puedo colisionar. //caja1Mesh = new MeshTipoCaja(caja1); //meshesColisionables = new ArrayList(); //meshesColisionables.Add(caja1Mesh); //// personaje.Update(); //escenarioActual.Update(); actualizarEscenario(); escenarioActual.AplicarGravedad(); foreach (Escenario escenario in escenarios.Values) { escenario.Update(); } escenarioActual.Colisiones(); if (Input.keyPressed(Key.Q)) { BoundingBox = !BoundingBox; } if (Input.keyPressed(Key.M)) { muteado = !muteado; } if (muteado) { cancionPpal.pause(); } else { cancionPpal.resume(); } if (cancionPpal.getStatus() != TgcMp3Player.States.Playing && !muteado) { cancionPpal.closeFile(); cancionPpal.play(true); } PostUpdate(); }
public override void Render(float elapsedTime) { drawer2D.BeginDrawSprite(); drawer2D.DrawSprite(backgroundSprite); drawer2D.EndDrawSprite(); text.render(); GuiMessage msg = gui.Update(elapsedTime, Input); // proceso el msg switch (msg.message) { case MessageType.WM_COMMAND: switch (msg.id) { case IDOK: if (msg_box_app_exit) { Application.Exit(); } if (msg_box_nueva_mision) { music.closeFile(); GameModel.ChangeLevel(); } break; case IDCANCEL: gui.EndDialog(); break; case ID_NUEVA_PARTIDA: gui.MessageBox("Nueva Partida", "TGC Gui Demo"); msg_box_nueva_mision = true; msg_box_app_exit = false; break; case ID_APP_EXIT: gui.MessageBox("Desea Salir?", "TGC Gui Demo"); msg_box_app_exit = true; msg_box_nueva_mision = false; break; case ID_CONTROLES: gui.MessageBoxControles("Controles", "TGC Gui Demo"); break; } break; default: break; } gui.Render(); }
public void startSound() { var currentState = mp3Player.getStatus(); if (currentState == TgcMp3Player.States.Playing) { if (currentFile != currentPlaying) { //Parar y reproducir MP3 mp3Player.closeFile(); mp3Player.play(true); currentPlaying = mp3Player.FileName; } } else { mp3Player.play(true); currentPlaying = mp3Player.FileName; } }
public override void close() { //corta la música al salir TgcMp3Player player = GuiController.Instance.Mp3Player; player.closeFile(); //dispose de blur effect.Dispose(); screenQuadVB.Dispose(); renderTarget2D.Dispose(); }
private void ReproducirMusica() { var player = new TgcMp3Player(); var currentState = player.getStatus(); if (currentState == TgcMp3Player.States.Open || currentState == TgcMp3Player.States.Stopped) { player.closeFile(); player.FileName = musicas[FuncionesMatematicas.Instance.NumeroAleatorioIntEntre(0, musicas.Count - 1)]; player.play(false); } }
private void Reubicar() { pelota.ReiniciarPelota(); sonido.closeFile(); sonido.FileName = MediaDir + "Music\\Acelerando.wav"; sonido.play(true); jugadores.ForEach(jugador => jugador.ReiniciarJugador()); turbos.ForEach(turbo => turbo.Reiniciar()); }
public SoundManager(Directorio directorio, Microsoft.DirectX.DirectSound.Device dsDevice) { Directorio = directorio; //Cargo archivo de sonido background mp3. mp3BackgroundPlayer.closeFile(); mp3BackgroundPlayer.FileName = directorio.SonidoFondo; mp3FruitPlayer.closeFile(); mp3FruitPlayer.FileName = directorio.SonidoFruta; //Cargo sonidos estaticos. SonidoSalto.loadSound(directorio.SonidoSalto, dsDevice); SonidoMoneda.loadSound(directorio.SonidoMoneda, dsDevice); SonidoDanio.loadSound(directorio.SonidoDanio, dsDevice); SonidoCaminar.loadSound(directorio.SonidoCaminar, dsDevice); //mp3SaltosPlayer.closeFile(); //mp3SaltosPlayer.FileName = directorio.SonidoSalto; }
/// <summary> /// Arranca a ejecutar un ejemplo. /// Para el ejemplo anterior, si hay alguno. /// </summary> public void ExecuteModel() { if (mp3Player.getStatus() == States.Playing) { mp3Player.closeFile(); } //Ejecutar Init try { Model.ResetDefaultConfig(); Model.DirectSound = DirectSound; Model.Input = Input; Model.Init(); panel3D.Focus(); } catch (Exception e) { MessageBox.Show(e.Message, "Error en Init() del juego", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public override void Dispose() { effect.Dispose(); recoltableItemEffect.Dispose(); wavesEffect.Dispose(); playerModel.Dispose(); bulletManager.Dispose(); skyBox.Dispose(); //skyBoxUndersea.Dispose(); surfacePlane.Dispose(); underseaTerrain.Dispose(); collectModel.Dispose(); shipHelmPoster.Dispose(); //Dispose de Meshes meshes.ForEach(x => x.Dispose()); shipHelmMesh.ForEach(x => x.Dispose()); historyModel.Dispose(); music.closeFile(); }
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(); } } }
private void Player() { TgcMp3Player player = new TgcMp3Player(); //if ((bool)GuiController.Instance.Modifiers["Musica"]) { if (player.getStatus() == TgcMp3Player.States.Open) { //Reproducir MP3 //FIXME //player.play(true); } if (player.getStatus() == TgcMp3Player.States.Stopped) { //Parar y reproducir MP3 player.closeFile(); player.play(true); } } /*else { if (player.getStatus() == TgcMp3Player.States.Playing) { //Parar el MP3 player.stop(); } }*/ }
/// <summary> /// Liberar recursos /// </summary> public static void Dispose() { Mp3Player.closeFile(); RuidoAmbienteOceano.dispose(); RuidoAmbienteSubmarino.dispose(); }
// <param name="elapsedTime">Tiempo en segundos transcurridos desde el último frame</param> public override void render(float elapsedTime) { Device d3dDevice = GuiController.Instance.D3dDevice; axisRotation += AXIS_ROTATION_SPEED * elapsedTime; float camaraY = (float)GuiController.Instance.Modifiers["camaraY"]; float camaraZ = (float)GuiController.Instance.Modifiers["camaraZ"]; camaraTerceraPersona.CambiarCamara(camaraY, camaraZ); //Obtener valor de UserVar (hay que castear) int valor = (int)GuiController.Instance.UserVars.getValue("variablePrueba"); #region //Radio de la nave string filePath = (string)GuiController.Instance.Modifiers["MP3-File"]; LoadMp3(filePath); TgcMp3Player player = GuiController.Instance.Mp3Player; TgcMp3Player.States currentState = player.getStatus(); if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.Y)) { if (currentState == TgcMp3Player.States.Open) { //Reproducir MP3 player.play(true); } if (currentState == TgcMp3Player.States.Stopped) { //Parar y reproducir MP3 player.closeFile(); player.play(true); } } else if (GuiController.Instance.D3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.O)) { if (currentState == TgcMp3Player.States.Playing) { //Parar el MP3 player.stop(); } } #endregion //Cargamos el Render Targer al cual se va a dibujar la escena 3D. Antes nos guardamos el surface original //En vez de dibujar a la pantalla, dibujamos a un buffer auxiliar, nuestro Render Target. pOldRT = d3dDevice.GetRenderTarget(0); Surface pSurf = renderTarget2D.GetSurfaceLevel(0); d3dDevice.SetRenderTarget(0, pSurf); d3dDevice.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); //Dibujamos la escena comun, pero en vez de a la pantalla al Render Target drawSceneToRenderTarget(d3dDevice, elapsedTime); //Liberar memoria de surface de Render Target pSurf.Dispose(); //Si quisieramos ver que se dibujo, podemos guardar el resultado a una textura en un archivo para debugear su resultado (ojo, es lento) //TextureLoader.Save(GuiController.Instance.ExamplesMediaDir + "Shaders\\render_target.bmp", ImageFileFormat.Bmp, renderTarget2D); //Ahora volvemos a restaurar el Render Target original (osea dibujar a la pantalla) d3dDevice.SetRenderTarget(0, pOldRT); //Luego tomamos lo dibujado antes y lo combinamos con una textura con efecto de alarma drawPostProcess(d3dDevice); nave.Renderizar(elapsedTime, obstaculos); NaveEnemiga1.MoverHaciaObjetivo(elapsedTime, nave.Modelo.Position); NaveEnemiga1.Renderizar(elapsedTime, obstaculos); #region Detectar Colisiones ColisionNave(elapsedTime); ColisionDisparos(elapsedTime); #endregion sol.BoundingBox.transform(sol.Transform); sol.Transform = TransformarSol(elapsedTime); GuiController.Instance.ThirdPersonCamera.Target = nave.Modelo.Position; //Limpiamos todas las transformaciones con la Matrix identidad sol.render(); d3dDevice.Transform.World = Matrix.Identity; Universo.renderAll(); }
public static void stop(TgcMp3Player music) { music?.stop(); music?.closeFile(); }
public override void Init() { var d3dDevice = D3DDevice.Instance.Device; moto = new Moto(MediaDir, new Vector3(0, 0, 0)); moto.init(); texturaPiso = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "SkyBoxTron\\bottom.png"); pisoPlane = new TgcPlane(); pisoPlane.Origin = new Vector3(-5000, 0, -5000); pisoPlane.Size = new Vector3(10000, 0, 10000); pisoPlane.Orientation = TgcPlane.Orientations.XZplane; pisoPlane.setTexture(texturaPiso); pisoPlane.updateValues(); piso = pisoPlane.toMesh("piso"); piso.AutoTransformEnable = true; camaraInterna = new camara(moto); Camara = camaraInterna; camaraInterna.rotateY(FastMath.ToRad(180)); skyBoxTron = new SkyBox(MediaDir); skyBoxTron.init(); texto = new TgcText2D(); texto.Color = Color.Red; texto.Align = TgcText2D.TextAlign.LEFT; texto.Text = "Perdiste, toca la tecla R para reiniciar"; texto.Size = new Size(700, 400); texto.Position = new Point(550, 150); textoModoDios = new TgcText2D(); textoModoDios.Color = Color.Red; textoModoDios.Text = "Modo Dios Activado"; textoModoDios.Position = new Point(0, 30); textoModoDios.Size = new Size(500, 200); controladorIA = new ControladorIA(); this.generarOponentes(); perdido = false; cajas = new List <TgcMesh>(); cajaConLuz = new TgcSceneLoader().loadSceneFromFile(MediaDir + Game.Default.pathCajaMetalica).Meshes[0]; cajaConLuz.Position = new Vector3(0, 0, -200); cajaConLuz.Scale = new Vector3(0.8f, 0.8f, 0.8f); efectoLuz = TgcShaders.loadEffect(ShadersDir + "MultiDiffuseLights.fx"); this.generarCajas(100); controladorIA.setObstaculosEscenario(cajas); gestorPowerUps = new GestorPowerUps(); mp3Player = new TgcMp3Player(); mp3Player.closeFile(); mp3Player.FileName = MediaDir + Game.Default.pathMusica; mp3Player.play(true); }
/// <summary> /// Se llama una sola vez, al principio cuando se ejecuta el ejemplo. /// Escribir aquí todo el código de inicialización: cargar modelos, texturas, estructuras de optimización, todo /// procesamiento que podemos pre calcular para nuestro juego. /// Borrar el codigo ejemplo no utilizado. /// </summary> public override void Init() { estrellasS.ForEach(e => e.AutoTransform = true); CustomVertex.PositionTextured[] screenQuadVertices = { new CustomVertex.PositionTextured(-1, 1, 1, 0, 0), new CustomVertex.PositionTextured(1, 1, 1, 1, 0), new CustomVertex.PositionTextured(-1, -1, 1, 0, 1), new CustomVertex.PositionTextured(1, -1, 1, 1, 1) }; //vertex buffer de los triangulos screenQuadVB = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, D3DDevice.Instance.Device, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); screenQuadVB.SetData(screenQuadVertices, 0, LockFlags.None); //Creamos un DepthStencil que debe ser compatible con nuestra definicion de renderTarget2D. depthStencil = D3DDevice.Instance.Device.CreateDepthStencilSurface(D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth, D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, DepthFormat.D24S8, MultiSampleType.None, 0, true); depthStencilOld = D3DDevice.Instance.Device.DepthStencilSurface; escena = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth, D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); propulsores = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth, D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); propulsoresBlurAux = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth, D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); propulsoresBlurAux2 = new Texture(D3DDevice.Instance.Device, D3DDevice.Instance.Device.PresentationParameters.BackBufferWidth, D3DDevice.Instance.Device.PresentationParameters.BackBufferHeight, 1, Usage.RenderTarget, Format.X8R8G8B8, Pool.Default); //Device de DirectX para crear primitivas. var d3dDevice = D3DDevice.Instance.Device; D3DDevice.Instance.Device.Transform.Projection = Matrix.PerspectiveFovLH(D3DDevice.Instance.FieldOfView, D3DDevice.Instance.AspectRatio, D3DDevice.Instance.ZNearPlaneDistance, D3DDevice.Instance.ZFarPlaneDistance * 1.8f); this.postProcessMerge = TgcShaders.loadEffect(this.ShadersDir + "PostProcess.fx"); this.blurEffect = TgcShaders.loadEffect(this.ShadersDir + "GaussianBlur.fx"); blurEffect.SetValue("screen_dx", d3dDevice.PresentationParameters.BackBufferWidth); blurEffect.SetValue("screen_dy", d3dDevice.PresentationParameters.BackBufferHeight); this.escenarios = new List <Escenario>(); this.enemigos = new List <NaveEnemiga>(); //Crear SkyBox skyBox = new TgcSkyBox(); skyBox.Center = new TGCVector3(0, 0, -2300f); skyBox.Size = new TGCVector3(10000, 10000, 18000); var texturesPath = MediaDir + "XWing\\Textures\\"; skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Up, texturesPath + "space.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Down, texturesPath + "space.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Left, texturesPath + "space.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Right, texturesPath + "space.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Front, texturesPath + "space.jpg"); skyBox.setFaceTexture(TgcSkyBox.SkyFaces.Back, texturesPath + "space.jpg"); skyBox.Init(); this.navePrincipal = new NaveEspacial(MediaDir, "xwing-TgcScene.xml", Color.DarkBlue, 10, 250, null, 250f); this.navePrincipal.ScaleFactor = TGCMatrix.Scaling(0.5f, 0.5f, 0.5f); this.navePrincipal.RotationVector = new TGCVector3(0, FastMath.PI_HALF, 0); this.navePrincipal.MovementVector = new TGCVector3(1200f, -1100f, 4000f); for (int i = 0; i < 5; i++) { escenarios.Add(Escenario.GenerarEscenarioDefault(MediaDir, i)); } for (int i = 0; i < enemigosAlMismoTiempo; i++) { enemigos.Add(new NaveEnemiga(MediaDir, "X-Wing-TgcScene.xml", dañoEnemigos, 500, navePrincipal)); enemigos[i].MovementVector = new TGCVector3(0, 0, 500000000000f); enemigos[i].CreateOOB(); } //escenarios.ForEach(es => es.generarTorre(MediaDir)); currentScene = escenarios[0]; this.navePrincipal.CreateOOB(); //Suelen utilizarse objetos que manejan el comportamiento de la camara. //Lo que en realidad necesitamos gráficamente es una matriz de View. //El framework maneja una cámara estática, pero debe ser inicializada. //Posición de la camara. var cameraPosition = new TGCVector3(0, 0, 0); //Quiero que la camara mire hacia el origen (0,0,0). var lookAt = new TGCVector3(-50000, -1, 0); //Configuro donde esta la posicion de la camara y hacia donde mira. Camara.SetCamera(cameraPosition, lookAt); //Internamente el framework construye la matriz de view con estos dos vectores. //Luego en nuestro juego tendremos que crear una cámara que cambie la matriz de view con variables como movimientos o animaciones de escenas. Camara = new CamaraStarWars(this.navePrincipal.GetPosition(), 20, 100); sol = TGCBox.fromSize(new TGCVector3(0, 5000, 4000), new TGCVector3(50, 50, 50), Color.Yellow); sol.AutoTransform = true; menu = new Menu(MediaDir, Input); //Cargo sonidos pathSonidoMenu = MediaDir + "Sound\\musica_menu.mp3"; pathSonidoAmbiente = MediaDir + "Music\\StarWarsMusic.mp3"; pathSonidoDisparo = MediaDir + "Music\\laserSound.wav"; if (menu.playSonidoMenu) { playerAmbiente.closeFile(); playerAmbiente.FileName = pathSonidoMenu; playerAmbiente.play(true); } drawer = new Drawer2D(); hud = new Hud(MediaDir, Input); //ShadowMap // Creo el shadowmap. // Format.R32F // Format.X8R8G8B8 g_pShadowMap = new Texture(D3DDevice.Instance.Device, SHADOWMAP_SIZE, SHADOWMAP_SIZE, 1, Usage.RenderTarget, Format.R32F, Pool.Default); // tengo que crear un stencilbuffer para el shadowmap manualmente // para asegurarme que tenga la el mismo tamano que el shadowmap, y que no tenga // multisample, etc etc. g_pDSShadow = D3DDevice.Instance.Device.CreateDepthStencilSurface(SHADOWMAP_SIZE, SHADOWMAP_SIZE, DepthFormat.D24S8, MultiSampleType.None, 0, true); // por ultimo necesito una matriz de proyeccion para el shadowmap, ya // que voy a dibujar desde el pto de vista de la luz. // El angulo tiene que ser mayor a 45 para que la sombra no falle en los extremos del cono de luz // de hecho, un valor mayor a 90 todavia es mejor, porque hasta con 90 grados es muy dificil // lograr que los objetos del borde generen sombras var aspectRatio = D3DDevice.Instance.AspectRatio; g_mShadowProj = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(50), aspectRatio, 50, 15000); D3DDevice.Instance.Device.Transform.Projection = TGCMatrix.PerspectiveFovLH(Geometry.DegreeToRadian(45.0f), aspectRatio, near_plane, far_plane).ToMatrix(); }