Exemplo n.º 1
0
 private float MovimientoArriba(TgcD3dInput Input)
 {
     return(Movimiento(Input.keyDown(Key.Up) || Input.keyDown(Key.W), "Caminar"));
 }
Exemplo n.º 2
0
        /// <summary>
        /// Obtiene la direccion a moverse por la camara en base a la entrada de teclado
        /// </summary>
        private Vector3 getMovementDirection(TgcD3dInput d3dInput)
        {
            Vector3 direction = new Vector3(0.0f, 0.0f, 0.0f);

            //Forward
            if (d3dInput.keyDown(Key.W))
            {
                if (!moveForwardsPressed)
                {
                    moveForwardsPressed = true;
                    currentVelocity     = new Vector3(currentVelocity.X, currentVelocity.Y, 0.0f);
                }

                direction.Z += 1.0f;
            }
            else
            {
                moveForwardsPressed = false;
            }

            //Backward
            if (d3dInput.keyDown(Key.S))
            {
                if (!moveBackwardsPressed)
                {
                    moveBackwardsPressed = true;
                    currentVelocity      = new Vector3(currentVelocity.X, currentVelocity.Y, 0.0f);
                }

                direction.Z -= 1.0f;
            }
            else
            {
                moveBackwardsPressed = false;
            }

            //Strafe right
            if (d3dInput.keyDown(Key.D))
            {
                if (!moveRightPressed)
                {
                    moveRightPressed = true;
                    currentVelocity  = new Vector3(0.0f, currentVelocity.Y, currentVelocity.Z);
                }

                direction.X += 1.0f;
            }
            else
            {
                moveRightPressed = false;
            }

            //Strafe left
            if (d3dInput.keyDown(Key.A))
            {
                if (!moveLeftPressed)
                {
                    moveLeftPressed = true;
                    currentVelocity = new Vector3(0.0f, currentVelocity.Y, currentVelocity.Z);
                }

                direction.X -= 1.0f;
            }
            else
            {
                moveLeftPressed = false;
            }

            //Jump
            if (d3dInput.keyDown(Key.Space))
            {
                if (!moveUpPressed)
                {
                    moveUpPressed   = true;
                    currentVelocity = new Vector3(currentVelocity.X, 0.0f, currentVelocity.Z);
                }

                direction.Y += 1.0f;
            }
            else
            {
                moveUpPressed = false;
            }

            //Crouch
            if (d3dInput.keyDown(Key.LeftControl))
            {
                if (!moveDownPressed)
                {
                    moveDownPressed = true;
                    currentVelocity = new Vector3(currentVelocity.X, 0.0f, currentVelocity.Z);
                }

                direction.Y -= 1.0f;
            }
            else
            {
                moveDownPressed = false;
            }

            return(direction);
        }
Exemplo n.º 3
0
 private float RotacionDerecha(TgcD3dInput Input)
 {
     return(Movimiento(Input.keyDown(Key.Right) || Input.keyDown(Key.D), "Rotacion"));
 }
Exemplo n.º 4
0
 private float MovimientoAbajo(TgcD3dInput Input)
 {
     return(Movimiento(Input.keyDown(Key.Down) || Input.keyDown(Key.S), "Caminar"));
 }
Exemplo n.º 5
0
 public bool keyDown(Key key)
 {
     return(keyboard.keyDown(key));
 }
Exemplo n.º 6
0
 private float RotacionIzquierda(TgcD3dInput Input)
 {
     return(Movimiento(Input.keyDown(Key.Left) || Input.keyDown(Key.A), "Rotacion"));
 }
        private void CheckInputs(float ElapsedTime, ref bool estaEnNave_)
        {
            int  w     = Input.keyDown(Key.W) ? 1 : 0;
            int  s     = Input.keyDown(Key.S) ? 1 : 0;
            int  d     = Input.keyDown(Key.D) ? 1 : 0;
            int  a     = Input.keyDown(Key.A) ? 1 : 0;
            int  space = Input.keyDown(Key.Space) ? 1 : 0;
            int  ctrl  = Input.keyDown(Key.LeftControl) ? 1 : 0;
            bool o     = Input.keyDown(Key.O);
            bool i     = Input.keyDown(Key.I);

            // nuestra "implementacion" del key pressed (porque nos da false todo el tiempo el de TGC)
            if (o)
            {
                o         = false;
                presionoO = true;
            }
            else
            {
                if (presionoO)
                {
                    o         = true;
                    presionoO = false;
                }
            }

            if (i)
            {
                i         = false;
                presionoI = true;
            }
            else
            {
                if (presionoI)
                {
                    i         = true;
                    presionoI = false;
                }
            }

            float fmov = w - s;        //foward movement
            float hmov = a - d;        //horizontal movement
            float vmov = space - ctrl; //vertical movement

            //Check for in-ship movement
            var LookDir = Camara.LookDir();
            var LeftDir = Camara.LeftDir();

            if (estaEnNave)
            {
                LookDir.Y = 0;
                LeftDir.Y = 0;
                vmov      = 0;
            }

            //Move player
            TGCVector3 movement = LookDir * fmov * speed + Camara.LeftDir() * hmov * speed + TGCVector3.Up * vmov * vspeed;

            movement  *= ElapsedTime;
            movement.Y = mesh.Position.Y + movement.Y < MIN_Y_POS ? 0 : movement.Y;

            if (IsOnTopOfWater())
            {
                movement.Y = FastMath.Min(movement.Y, 0);
            }

            Move(movement, ElapsedTime);

            if (i)
            {
                if (!Hud.IsCurrentStatus(Hud.Status.MainMenu) && !Hud.IsCurrentStatus(Hud.Status.GameOver))
                {
                    if (!Hud.IsCurrentStatus(Hud.Status.Inventory) && !Hud.IsCurrentStatus(Hud.Status.Crafting))
                    {
                        if (!estaEnNave)
                        {
                            Hud.ChangeStatus(Hud.Status.Inventory);
                        }
                        else
                        {
                            Hud.ChangeStatus(Hud.Status.Crafting);
                        }
                    }
                    else
                    {
                        Hud.ChangeStatus(Hud.Status.Gameplay);
                    }
                }
            }

            if (o)
            {
                estaEnNave_ = !estaEnNave_;
                walking.stop();
                if (estaEnNave_)
                {
                    // guardar la posicion en la que estaba para que cuando vuelva, ponerlo en esa posicion anterior
                    // posiciono dentro de nave
                    posicionMar   = mesh.Position;
                    mesh.Position = posicionInteriorNave;
                }
                else
                {
                    mesh.Position = posicionMar;
                }

                Hud.ChangeStatus(Hud.Status.Gameplay);
            }

            //Dev
            bool p = Input.keyDown(Key.P);

            // usar nuestra implementacion del key pressed
            if (p)
            {
                p         = false;
                presionoP = true;
            }
            else
            {
                if (presionoP)
                {
                    p         = true;
                    presionoP = false;
                }
            }
            if (p)
            {
                godmode = !godmode; GodMode(godmode);
            }
        }
Exemplo n.º 8
0
        // simple physics
        // computa todas las fuerzas que invervienen
        // necesito el Input, ya que las teclas generan fuerzas
        public void computeForces(TgcD3dInput Input, float ElapsedTime)
        {
            // limpio cualquier otra fuerza
            acel_angular = 0.0f;

            float dx = 3.0f;

            if ((Input.keyDown(Key.Left)) && X < dr)
            {
                // MODO ARCADE: muevo directo de carril
                if (Input.keyDown(Key.LeftShift))
                {
                    X = dr - 20;
                }
                else
                {
                    X += dx;
                }
                acel_angular = 2.5f;
            }
            else
            if ((Input.keyDown(Key.Right)) && X > -dr)
            {
                if (Input.keyDown(Key.LeftShift))
                {
                    X = -dr + 20;
                }
                else
                {
                    X -= dx;
                }
                acel_angular = -2.5f;
            }

            // Modo piano
            if ((Input.keyDown(Key.NumPad6)))
            {
                X            = -dr + 30;
                acel_angular = -2.5f;
            }
            else
            if ((Input.keyDown(Key.NumPad5)))
            {
                X            = 0;
                acel_angular = 0f;
            }
            else
            if ((Input.keyDown(Key.NumPad4)))
            {
                X            = dr - 30;
                acel_angular = 2.5f;
            }



            if (X < -dr)
            {
                X = -dr;
            }
            else
            if (X > dr)
            {
                X = dr;
            }
        }
        /// <summary>
        /// Actualizar eventos
        /// </summary>
        public void update()
        {
            TgcD3dInput   input      = GuiController.Instance.D3dInput;
            TgcPickingRay pickingRay = editablePoly.Control.PickingRay;

            switch (currentState)
            {
            case State.Init:

                acumMovement = Vector3.Empty;
                gizmoMesh.unSelect();

                //Iniciar seleccion de eje
                if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    //Buscar colision con ejes del gizmo
                    pickingRay.updateRay();
                    gizmoMesh.selectAxisByPicking(pickingRay.Ray);
                    if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.X)
                    {
                        initMouseP3d = editablePoly.Control.Grid.getPickingX(pickingRay.Ray, gizmoMesh.GizmoCenter);
                    }
                    else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.Y)
                    {
                        initMouseP3d = editablePoly.Control.Grid.getPickingY(pickingRay.Ray, gizmoMesh.GizmoCenter);
                    }
                    else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.Z)
                    {
                        initMouseP3d = editablePoly.Control.Grid.getPickingZ(pickingRay.Ray, gizmoMesh.GizmoCenter);
                    }
                    else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.XZ)
                    {
                        initMouseP3d = editablePoly.Control.Grid.getPickingXZ(pickingRay.Ray, gizmoMesh.GizmoCenter);
                    }
                    else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.XY)
                    {
                        initMouseP3d = editablePoly.Control.Grid.getPickingXY(pickingRay.Ray, gizmoMesh.GizmoCenter);
                    }
                    else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.YZ)
                    {
                        initMouseP3d = editablePoly.Control.Grid.getPickingYZ(pickingRay.Ray, gizmoMesh.GizmoCenter);
                    }

                    //Si eligio un eje, iniciar dragging
                    if (gizmoMesh.SelectedAxis != TranslateGizmoMesh.Axis.None)
                    {
                        currentState = State.Dragging;
                    }
                    else
                    {
                        if (input.buttonPressed(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                        {
                            bool additive = input.keyDown(Microsoft.DirectX.DirectInput.Key.LeftControl) || input.keyDown(Microsoft.DirectX.DirectInput.Key.RightControl);
                            editablePoly.CurrentState = EditablePoly.State.SelectObject;
                            editablePoly.doDirectSelection(additive);
                        }
                    }
                }
                //Hacer mouse over sobre los ejes
                else
                {
                    //Buscar colision con eje con Picking
                    pickingRay.updateRay();
                    gizmoMesh.selectAxisByPicking(pickingRay.Ray);
                }

                break;

            case State.Dragging:

                //Mover
                if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    pickingRay.updateRay();
                    Vector3 endMouseP3d = initMouseP3d;

                    //Solo se mueve un eje
                    Vector3 currentMove = new Vector3(0, 0, 0);
                    if (gizmoMesh.isSingleAxis(gizmoMesh.SelectedAxis))
                    {
                        //Desplazamiento en eje X
                        if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.X)
                        {
                            endMouseP3d   = editablePoly.Control.Grid.getPickingX(pickingRay.Ray, gizmoMesh.GizmoCenter);
                            currentMove.X = endMouseP3d.X - initMouseP3d.X;
                        }
                        //Desplazamiento en eje Y
                        else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.Y)
                        {
                            endMouseP3d   = editablePoly.Control.Grid.getPickingY(pickingRay.Ray, gizmoMesh.GizmoCenter);
                            currentMove.Y = endMouseP3d.Y - initMouseP3d.Y;
                        }
                        //Desplazamiento en eje Z
                        else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.Z)
                        {
                            endMouseP3d   = editablePoly.Control.Grid.getPickingZ(pickingRay.Ray, gizmoMesh.GizmoCenter);
                            currentMove.Z = endMouseP3d.Z - initMouseP3d.Z;
                        }
                    }
                    //Desplazamiento en dos ejes
                    else
                    {
                        //Plano XZ
                        if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.XZ)
                        {
                            endMouseP3d   = editablePoly.Control.Grid.getPickingXZ(pickingRay.Ray, gizmoMesh.GizmoCenter);
                            currentMove.X = endMouseP3d.X - initMouseP3d.X;
                            currentMove.Z = endMouseP3d.Z - initMouseP3d.Z;
                        }
                        //Plano XY
                        else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.XY)
                        {
                            endMouseP3d   = editablePoly.Control.Grid.getPickingXY(pickingRay.Ray, gizmoMesh.GizmoCenter);
                            currentMove.X = endMouseP3d.X - initMouseP3d.X;
                            currentMove.Y = endMouseP3d.Y - initMouseP3d.Y;
                        }
                        //Plano YZ
                        else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.YZ)
                        {
                            endMouseP3d   = editablePoly.Control.Grid.getPickingYZ(pickingRay.Ray, gizmoMesh.GizmoCenter);
                            currentMove.Y = endMouseP3d.Y - initMouseP3d.Y;
                            currentMove.Z = endMouseP3d.Z - initMouseP3d.Z;
                        }
                    }

                    //Actualizar pos del mouse 3D para proximo cuadro
                    initMouseP3d = endMouseP3d;

                    //Ajustar currentMove con Snap to grid
                    if (editablePoly.Control.SnapToGridEnabled)
                    {
                        snapMovementToGrid(ref currentMove.X, ref acumMovement.X, editablePoly.Control.SnapToGridCellSize);
                        snapMovementToGrid(ref currentMove.Y, ref acumMovement.Y, editablePoly.Control.SnapToGridCellSize);
                        snapMovementToGrid(ref currentMove.Z, ref acumMovement.Z, editablePoly.Control.SnapToGridCellSize);
                    }
                    if (currentMove.LengthSq() > 0.1f)
                    {
                        //Mover objetos
                        foreach (EditPolyPrimitive p in editablePoly.SelectionList)
                        {
                            p.move(currentMove);
                        }

                        //Mover ejes
                        gizmoMesh.moveGizmo(currentMove);

                        //Actualizar mesh
                        editablePoly.setDirtyValues(false);

                        //Actualizar datos de modify
                        //Control.updateModifyPanel();
                    }
                }

                //Soltar movimiento
                else if (input.buttonUp(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    currentState = State.Init;
                    gizmoMesh.unSelect();
                }


                break;
            }



            //Ajustar tamaño de ejes
            gizmoMesh.setCenter(gizmoMesh.GizmoCenter, editablePoly.Control.Camera);
        }
Exemplo n.º 10
0
        public override void render(float elapsedTime)
        {
            Microsoft.DirectX.Direct3D.Device d3dDevice = GuiController.Instance.D3dDevice;

            //Obtenemos acceso al objeto que maneja input de mouse y teclado del framework
            TgcD3dInput input = GuiController.Instance.D3dInput;

            //Declaramos un vector de movimiento inicializado todo en cero.
            //El movimiento sobre el suelo es sobre el plano XZ.
            //El movimiento en altura es sobre el eje Y.
            //Sobre XZ nos movemos con las flechas del teclado o con las letas WASD.
            //Sobre el eje Y nos movemos con Space y Ctrl.
            Vector3 movement = new Vector3(0, 0, 0);

            //Movernos de izquierda a derecha, sobre el eje X.
            if (input.keyDown(Key.Left) || input.keyDown(Key.A))
            {
                movement.X = 1;
            }
            else if (input.keyDown(Key.Right) || input.keyDown(Key.D))
            {
                movement.X = -1;
            }

            //Movernos arriba y abajo, sobre el eje Y.
            if (input.keyDown(Key.Space))
            {
                movement.Y = 1;
            }
            else if (input.keyDown(Key.LeftControl) || input.keyDown(Key.RightControl))
            {
                movement.Y = -1;
            }

            //Movernos adelante y atras, sobre el eje Z.
            if (input.keyDown(Key.Up) || input.keyDown(Key.W))
            {
                movement.Z = -1;
            }
            else if (input.keyDown(Key.Down) || input.keyDown(Key.S))
            {
                movement.Z = 1;
            }


            //Multiplicar movimiento por velocidad y elapsedTime
            movement *= MOVEMENT_SPEED * elapsedTime;

            //Aplicar movimiento
            box.move(movement);


            box.render();
        }
Exemplo n.º 11
0
        public void Update(TgcD3dInput input)
        {
            dynamicsWorld.StepSimulation(1 / 60f, 100);
            var strength = 10.30f;
            var angle    = 5;
            var moving   = false;

            #region Comoportamiento

            if (input.keyDown(Key.W))
            {
                moving = true;
                //Activa el comportamiento de la simulacion fisica para la capsula
                capsuleRigidBody.ActivationState = ActivationState.ActiveTag;
                capsuleRigidBody.AngularVelocity = TGCVector3.Empty.ToBulletVector3();
                capsuleRigidBody.ApplyCentralImpulse(-strength * director.ToBulletVector3());
            }

            if (input.keyDown(Key.S))
            {
                moving = true;
                //Activa el comportamiento de la simulacion fisica para la capsula
                capsuleRigidBody.ActivationState = ActivationState.ActiveTag;
                capsuleRigidBody.AngularVelocity = TGCVector3.Empty.ToBulletVector3();
                capsuleRigidBody.ApplyCentralImpulse(strength * director.ToBulletVector3());
            }

            if (input.keyDown(Key.A))
            {
                director.TransformCoordinate(TGCMatrix.RotationY(-angle * 0.01f));
                personaje.Transform             = TGCMatrix.Translation(TGCVector3.Empty) * TGCMatrix.RotationY(-angle * 0.01f) * new TGCMatrix(capsuleRigidBody.InterpolationWorldTransform);
                capsuleRigidBody.WorldTransform = personaje.Transform.ToBsMatrix;
            }

            if (input.keyDown(Key.D))
            {
                director.TransformCoordinate(TGCMatrix.RotationY(angle * 0.01f));
                personaje.Transform             = TGCMatrix.Translation(TGCVector3.Empty) * TGCMatrix.RotationY(angle * 0.01f) * new TGCMatrix(capsuleRigidBody.InterpolationWorldTransform);
                capsuleRigidBody.WorldTransform = personaje.Transform.ToBsMatrix;
            }

            if (input.keyPressed(Key.Space))
            {
                //Activa el comportamiento de la simulacion fisica para la capsula
                capsuleRigidBody.ActivationState = ActivationState.ActiveTag;
                capsuleRigidBody.ApplyCentralImpulse(new TGCVector3(0, 80 * strength, 0).ToBulletVector3());
            }

            #endregion Comoportamiento

            #region Animacion

            if (moving)
            {
                personaje.playAnimation("Caminando", true);
            }
            else
            {
                personaje.playAnimation("Parado", true);
            }

            #endregion Animacion
        }
Exemplo n.º 12
0
        private Lanzar lanzar;   //TODO esto esta para poder solucionar la sincronizacion, pensar mejor!!!

        #endregion Atributos

        #region Comportamientos

        public List <Comando> ProcesarEntradasTeclado()
        {
            comandosSeleccionados.Clear();

            #region Paquete de fuciones (Fx)

            //Si preciono para ver el menú de ayuda
            if (d3dInput.keyDown(Key.F1))
            {
                comandosSeleccionados.Add(new Ayuda(TextoDeComandos()));
                return(comandosSeleccionados);
            }
            //Si preciono para usar camara en primera persona
            if (d3dInput.keyDown(Key.F2))
            {
                comandosSeleccionados.Add(new CambiarCamara(CambiarCamara.PrimeraPersona));
                return(comandosSeleccionados);
            }
            //Si preciono para usar camara en tercera persona
            if (d3dInput.keyDown(Key.F3))
            {
                comandosSeleccionados.Add(new CambiarCamara(CambiarCamara.TerceraPersona));
                return(comandosSeleccionados);
            }
            //Si preciono para bajar la camara
            if (d3dInput.keyDown(Key.F5))
            {
                comandosSeleccionados.Add(new MoverCamara(MoverCamara.BajarCamara));
                return(comandosSeleccionados);
            }
            //Si preciono para subir la camara
            if (d3dInput.keyDown(Key.F6))
            {
                comandosSeleccionados.Add(new MoverCamara(MoverCamara.SubirCamara));
                return(comandosSeleccionados);
            }
            //Si preciono para Acercar la camara
            if (d3dInput.keyDown(Key.F7))
            {
                comandosSeleccionados.Add(new MoverCamara(MoverCamara.AcercarCamara));
                return(comandosSeleccionados);
            }
            //Si preciono para alajar la camara
            if (d3dInput.keyDown(Key.F8))
            {
                comandosSeleccionados.Add(new MoverCamara(MoverCamara.AlejarCamara));
                return(comandosSeleccionados);
            }

            #endregion Paquete de fuciones (Fx)

            #region Paquete de movimientos principales acelerados

            //Si preciono para caminar más rápido para adelante
            if (d3dInput.keyDown(Key.RightShift) ||
                d3dInput.keyDown(Key.LeftShift) && (d3dInput.keyDown(Key.W) || d3dInput.keyDown(Key.Up)))
            {
                var mover = new Mover(-1f);
                mover.MovimientoRapido = true;
                comandosSeleccionados.Add(mover);
                //return this.comandosSeleccionados;
            }

            //Si preciono para caminar más rápido para atras
            if (d3dInput.keyDown(Key.RightShift) ||
                d3dInput.keyDown(Key.LeftShift) && (d3dInput.keyDown(Key.S) || d3dInput.keyDown(Key.Down)))
            {
                var mover = new Mover(1f);
                mover.MovimientoRapido = true;
                comandosSeleccionados.Add(mover);
                //return this.comandosSeleccionados;
            }

            //Si preciono para rotar más rápido para la derecha
            if (d3dInput.keyDown(Key.RightShift) ||
                d3dInput.keyDown(Key.LeftShift) && (d3dInput.keyDown(Key.Right) || d3dInput.keyDown(Key.D)))
            {
                var rotar = new Girar(1f);
                rotar.MovimientoRapido = true;
                comandosSeleccionados.Add(rotar);
                //return this.comandosSeleccionados;
            }

            //Si preciono para rotar más rápido para la izquierda
            if (d3dInput.keyDown(Key.RightShift) ||
                d3dInput.keyDown(Key.LeftShift) && (d3dInput.keyDown(Key.Left) || d3dInput.keyDown(Key.A)))
            {
                var rotar = new Girar(-1f);
                rotar.MovimientoRapido = true;
                comandosSeleccionados.Add(rotar);
                //return this.comandosSeleccionados;
            }
            if (comandosSeleccionados.Count > 0)
            {
                return(comandosSeleccionados);
            }

            #endregion Paquete de movimientos principales acelerados

            #region Paquete de movimientos principales

            //Movimiento para adelante
            if (d3dInput.keyDown(Key.W) || d3dInput.keyDown(Key.Up))
            {
                Comando accion = new Mover(-1f);
                comandosSeleccionados.Add(accion);
                //return this.comandosSeleccionados;
            }

            //Movimiento para Atras
            if (d3dInput.keyDown(Key.S) || d3dInput.keyDown(Key.Down))
            {
                Comando accion = new Mover(1f);
                comandosSeleccionados.Add(accion);
                //return this.comandosSeleccionados;
            }

            //Rotar Derecha
            if (d3dInput.keyDown(Key.Right) || d3dInput.keyDown(Key.D))
            {
                Comando rotar = new Girar(1f);
                comandosSeleccionados.Add(rotar);
                //return this.comandosSeleccionados;
            }

            //Rotar Izquierda
            if (d3dInput.keyDown(Key.Left) || d3dInput.keyDown(Key.A))
            {
                Comando rotar = new Girar(-1f);
                comandosSeleccionados.Add(rotar);
                //return this.comandosSeleccionados;
            }
            if (comandosSeleccionados.Count > 0)
            {
                return(comandosSeleccionados);
            }

            #endregion Paquete de movimientos principales

            #region Paquete de acciones con 2 teclas

            //Tirar un elemento
            if (d3dInput.keyDown(Key.T) && d3dInput.keyDown(Key.D1))
            {
                Comando accion = new Tirar(Tirar.Uno);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }
            if (d3dInput.keyDown(Key.T) && d3dInput.keyDown(Key.D2))
            {
                Comando accion = new Tirar(Tirar.Dos);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }
            if (d3dInput.keyDown(Key.T) && d3dInput.keyDown(Key.D3))
            {
                Comando accion = new Tirar(Tirar.Tres);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }
            if (d3dInput.keyDown(Key.T) && d3dInput.keyDown(Key.D4))
            {
                Comando accion = new Tirar(Tirar.Cuatro);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }
            if (d3dInput.keyDown(Key.T) && d3dInput.keyDown(Key.D5))
            {
                Comando accion = new Tirar(Tirar.Cinco);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }
            if (d3dInput.keyDown(Key.T) && d3dInput.keyDown(Key.D6))
            {
                Comando accion = new Tirar(Tirar.Seis);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }
            if (d3dInput.keyDown(Key.T) && d3dInput.keyDown(Key.D7))
            {
                Comando accion = new Tirar(Tirar.Siete);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }
            if (d3dInput.keyDown(Key.T) && d3dInput.keyDown(Key.D8))
            {
                Comando accion = new Tirar(Tirar.Ocho);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }
            if (d3dInput.keyDown(Key.T) && d3dInput.keyDown(Key.D9))
            {
                Comando accion = new Tirar(Tirar.Nueve);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }

            #endregion Paquete de acciones con 2 teclas

            #region Paquete de acciones con 1 tecla

            //Seleccion de Arma palo
            if (d3dInput.keyDown(Key.D1))
            {
                comandosSeleccionados.Add(new ApagarAntorcha());
                Comando accion = new Seleccionar(Seleccionar.NumeroUno);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }

            //Seleccion de Arma Hacha
            if (d3dInput.keyDown(Key.D2))
            {
                comandosSeleccionados.Add(new ApagarAntorcha());
                Comando accion = new Seleccionar(Seleccionar.NumeroDos);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }

            //Seleccion Juntar
            if (d3dInput.keyDown(Key.J))
            {
                Comando accion = new Interactuar(Interactuar.Juntar);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }

            //Seleccion Encender
            if (d3dInput.keyDown(Key.E))
            {
                Comando accion = new Interactuar(Interactuar.Encender);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }

            //Seleccion Consumir
            if (d3dInput.keyDown(Key.C))
            {
                Comando accion = new Interactuar(Interactuar.Consumir);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }

            //Abrir
            if (d3dInput.keyDown(Key.B))
            {
                Comando accion = new Interactuar(Interactuar.Abrir);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }

            //Juntar todo
            if (d3dInput.keyDown(Key.Y))
            {
                Comando accion = new Interactuar(Interactuar.JuntarTodo);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }

            //Dejar Todo
            if (d3dInput.keyDown(Key.U))
            {
                Comando accion = new Interactuar(Interactuar.DejarTodo);
                comandosSeleccionados.Add(accion);
                return(comandosSeleccionados);
            }

            //Pegar una piña
            if (d3dInput.keyDown(Key.RightControl))
            {
                if (golpear == null)
                {
                    golpear = new Golpear(Golpear.Pegar);
                }
                else
                {
                    golpear.GolpeActual = Golpear.Pegar;
                }
                comandosSeleccionados.Add(golpear);
                return(comandosSeleccionados);
            }

            //Pegar una patada
            if (d3dInput.keyDown(Key.LeftControl))
            {
                if (golpear == null)
                {
                    golpear = new Golpear(Golpear.Patear);
                }
                else
                {
                    golpear.GolpeActual = Golpear.Patear;
                }
                comandosSeleccionados.Add(golpear);
                return(comandosSeleccionados);
            }

            //Saltar
            if (d3dInput.keyDown(Key.Space))
            {
                if (saltar == null)
                {
                    saltar = new Saltar(Saltar.EnLugar);
                }
                else if (saltar.Movimiento.Finalizo)
                {
                    saltar = new Saltar(Saltar.EnLugar);
                }
                comandosSeleccionados.Add(saltar);
                return(comandosSeleccionados);
            }

            //Lanza un elemento con fuerza
            if (d3dInput.keyDown(Key.P))
            {
                if (lanzar == null)
                {
                    lanzar = new Lanzar();
                    comandosSeleccionados.Add(lanzar);
                }
                else if (lanzar.Movimiento != null && lanzar.Movimiento.Finalizo)
                {
                    lanzar = null;
                    lanzar = new Lanzar();
                    comandosSeleccionados.Add(lanzar);
                }
                return(comandosSeleccionados);
            }

            //Saltar adelante
            if (d3dInput.keyDown(Key.Z))
            {
                if (saltar == null)
                {
                    saltar = new Saltar(Saltar.Adelante);
                }
                else if (saltar.Movimiento.Finalizo)
                {
                    saltar = new Saltar(Saltar.Adelante);
                }
                comandosSeleccionados.Add(saltar);
                return(comandosSeleccionados);
            }

            //Imprimir menu de mochila del personaje
            if (d3dInput.keyDown(Key.M))
            {
                comandosSeleccionados.Add(new Menu(Menu.Mochila));
                return(comandosSeleccionados);
            }

            //Encender una antorcha
            if (d3dInput.keyDown(Key.L))
            {
                comandosSeleccionados.Add(new EncenderAntorcha());
                return(comandosSeleccionados);
            }

            comandosSeleccionados.Add(new Interactuar(Interactuar.Parado));
            return(comandosSeleccionados);

            #endregion Paquete de acciones con 1 tecla
        }
Exemplo n.º 13
0
        public void update(float dt, C_Hoja[] hojas, C_Earth the_earth, C_Earth the_earth2, C_Water water, TgcSkyBox skyBox)
        {
            time += dt;
            TgcD3dInput d3dInput = GuiController.Instance.D3dInput;

            //gravedad (si no estoy en contacto con algo, caer)
            if (glued == null)
            {
                playMove.Y -= 30f * dt;
            }
            else
            {
                playMove.Y = 0;
            }
            //si estoy en el suelo y BARRA ESPACIADORA => Saltar
            if (move_able & d3dInput.keyDown(Key.Space) && (glued != null))
            {
                playMove.Y = 30f;
                sound_b.render();
            }
            //M => Bolquear movimiento
            if (d3dInput.keyDown(Key.M))
            {
                move_able = !move_able;
            }

            //calcular movimiento hacia adelante y costado
            float moveForward = 0f;
            float moveLateral = 0f;

            if (move_able & d3dInput.keyDown(Key.W))
            {
                moveForward = 1f;
            }
            if (move_able & d3dInput.keyDown(Key.S))
            {
                moveForward = -1f;
            }
            if (move_able & d3dInput.keyDown(Key.A))
            {
                moveLateral = 1f;
            }
            if (move_able & d3dInput.keyDown(Key.D))
            {
                moveLateral = -1f;
            }

            //rotar camara
            rotation = 0;
            if (d3dInput.keyDown(Key.Q))
            {
                rotation = 1;
            }
            if (d3dInput.keyDown(Key.E))
            {
                rotation = -1;
            }

            //calcular vectores de movimiento, basado en camara
            playMove.X = playMove.Z = 0f;
            if (moveLateral != 0 | moveForward != 0)
            {
                Vector3 camDir = GuiController.Instance.CurrentCamera.getLookAt() - GuiController.Instance.CurrentCamera.getPosition();
                camDir.Y = 0;
                Vector3 moveDir = Vector3.Normalize(camDir);
                playMove.X = moveDir.X * moveForward - moveDir.Z * moveLateral;
                playMove.Z = moveDir.Z * moveForward + moveDir.X * moveLateral;
                //"normalizar" para tener velocidad maxima
                float modXZ = (float)Math.Sqrt(playMove.X * playMove.X + playMove.Z * playMove.Z);
                playMove.X = playMove.X * 75f / modXZ;
                playMove.Z = playMove.Z * 75f / modXZ;
            }

            //si esta en contacto con una hoja, moverse con ella
            if (glued != null)
            {
                if (glued.id == 'h')
                {
                    C_Hoja h = (C_Hoja)glued;
                    playMove += h.vel;
                }
            }
            Vector3 old_pos = pos;

            pos += playMove * dt;
            mesh.BoundingBox.move(playMove * dt);

            bool collide = false;

            TgcCollisionUtils.BoxBoxResult result;

            //si choca contra una cara del skybox, frenarla
            foreach (TgcMesh face in skyBox.Faces)
            {
                result = TgcCollisionUtils.classifyBoxBox(mesh.BoundingBox, face.BoundingBox);
                if (result == TgcCollisionUtils.BoxBoxResult.Adentro || result == TgcCollisionUtils.BoxBoxResult.Atravesando)
                {
                    collide = true;
                    break;
                }
            }
            if (collide)
            {
                Vector3 dif = old_pos - pos;
                dif.Y = 0f;
                pos  += dif;
                mesh.BoundingBox.move(dif);
            }


            //cuando esta muriendo, si deja de estar en contacto con agua (la termino de atravesar) resetear
            if (dieing)
            {
                result = TgcCollisionUtils.classifyBoxBox(mesh.BoundingBox, water.BoundingBox());
                if (result == TgcCollisionUtils.BoxBoxResult.Atravesando)
                {
                    sound_c.render();
                }
                if (result != TgcCollisionUtils.BoxBoxResult.Adentro && result != TgcCollisionUtils.BoxBoxResult.Atravesando)
                {
                    reset(the_earth);
                }
                return;
            }


            //chequear si sihue en contacto con el objeto con el que estaba en contacto
            if (glued != null)
            {
                result = TgcCollisionUtils.BoxBoxResult.Afuera;
                if (glued.id == 'e')
                {
                    C_Earth e = (C_Earth)glued;
                    result = TgcCollisionUtils.classifyBoxBox(mesh.BoundingBox, e.BoundingBox());
                }
                else if (glued.id == 'h')
                {
                    C_Hoja h = (C_Hoja)glued;
                    result = TgcCollisionUtils.classifyBoxBox(mesh.BoundingBox, h.BoundingBox());
                }
                else if (glued.id == 'w')
                {
                    C_Water w = (C_Water)glued;
                    result = TgcCollisionUtils.classifyBoxBox(mesh.BoundingBox, w.BoundingBox());
                }

                if (result == TgcCollisionUtils.BoxBoxResult.Encerrando || result == TgcCollisionUtils.BoxBoxResult.Adentro || result == TgcCollisionUtils.BoxBoxResult.Atravesando)
                {
                    return;
                }
                glued = null;
            }

            //colisionar con hojas
            foreach (C_Hoja x in hojas)
            {
                result = TgcCollisionUtils.classifyBoxBox(mesh.BoundingBox, x.BoundingBox());
                if (result == TgcCollisionUtils.BoxBoxResult.Adentro || result == TgcCollisionUtils.BoxBoxResult.Atravesando)
                {
                    glued = x;
                    return;
                }
            }
            //colisionar con la tierra
            result = TgcCollisionUtils.classifyBoxBox(mesh.BoundingBox, the_earth.BoundingBox());
            if (result == TgcCollisionUtils.BoxBoxResult.Adentro || result == TgcCollisionUtils.BoxBoxResult.Atravesando)
            {
                glued = the_earth;
                return;
            }
            //colisionar con la otra tierra
            result = TgcCollisionUtils.classifyBoxBox(mesh.BoundingBox, the_earth2.BoundingBox());
            if (result == TgcCollisionUtils.BoxBoxResult.Adentro || result == TgcCollisionUtils.BoxBoxResult.Atravesando)
            {
                glued = the_earth2;
                return;
            }
            //colisionar con agua
            result = TgcCollisionUtils.classifyBoxBox(mesh.BoundingBox, water.BoundingBox());
            if (result == TgcCollisionUtils.BoxBoxResult.Adentro || result == TgcCollisionUtils.BoxBoxResult.Atravesando)
            {
                dieing = true;
            }
            return;
        }
Exemplo n.º 14
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();
        }
        public void Update(TgcD3dInput Input)
        {
            physicWorld.Update();

            if (!GameModel.modoGod)
            {
                manejarCreacionZombies();
            }
            else
            {
                if (Input.keyDown(Key.Z))
                {
                    crearZombies();
                    quitarPlantasIlegales();
                    chequearExplosionesActivas();
                }
                if (Input.keyDown(Key.X))
                {
                    bombardear();
                }
            }

            plantas.ForEach(P => P.Update(Input));

            #region manejoTablero
            tablero.Update(Input);

            if (tablero.plataformaSeleccionada == null)
            {
                return;
            }
            if (tablero.plataformaSeleccionada.ocupado)
            {
                return;
            }
            posicionSeleccionada = tablero.plataformaSeleccionada.mesh.Position;
            #endregion

            #region chequearInput
            if (Input.keyDown(Key.NumPad1) || Input.keyDown(Key.D1))
            {
                addPlanta(FactoryPlanta.crearCanion(posicionSeleccionada, this, tablero.plataformaSeleccionada));
            }
            if (Input.keyDown(Key.NumPad2) || Input.keyDown(Key.D2))
            {
                addPlanta(FactoryPlanta.crearGirasol(posicionSeleccionada, this, tablero.plataformaSeleccionada));
            }
            if (Input.keyDown(Key.NumPad3) || Input.keyDown(Key.D3))
            {
                addPlanta(FactoryPlanta.crearCongelador(posicionSeleccionada, this, tablero.plataformaSeleccionada));
            }
            if (Input.keyDown(Key.NumPad4) || Input.keyDown(Key.D4))
            {
                addPlanta(FactoryPlanta.crearMina(posicionSeleccionada, this, tablero.plataformaSeleccionada));
            }
            if (Input.keyDown(Key.NumPad5) || Input.keyDown(Key.D5))
            {
                addPlanta(FactoryPlanta.crearChile(posicionSeleccionada, this, tablero.plataformaSeleccionada));
            }
            if (Input.keyDown(Key.NumPad6) || Input.keyDown(Key.D6))
            {
                addPlanta(FactoryPlanta.crearNuez(posicionSeleccionada, this, tablero.plataformaSeleccionada));
            }
            if (Input.keyDown(Key.NumPad7) || Input.keyDown(Key.D7))
            {
                addPlanta(FactoryPlanta.crearSuperCanion(posicionSeleccionada, this, tablero.plataformaSeleccionada));
            }

            #endregion
        }
Exemplo n.º 16
0
        /// <summary>
        /// Actualizar el estado interno de la cámara en cada frame
        /// </summary>
        public void updateCamera()
        {
            if (!Enable)
            {
                return;
            }

            float       elapsedTime = GuiController.Instance.ElapsedTime;
            TgcD3dInput input       = GuiController.Instance.D3dInput;

            if (input.keyPressed(Key.L))
            {
                LockMouse = !LockMouse;
            }

            if (!LockMouse)
            {
                return;
            }

            // posicion
            //
            bool    moved    = false;
            Vector3 movement = new Vector3(0.0f, 0.0f, 0.0f);

            if (input.keyDown(Key.W))
            {
                movement += forward * (MovementSpeed * elapsedTime * ForwardFactor);
                moved     = true;
            }

            if (input.keyDown(Key.A))
            {
                movement += xAxis * (-MovementSpeed * elapsedTime);
                moved     = true;
            }

            if (input.keyDown(Key.S))
            {
                movement += forward * (-MovementSpeed * elapsedTime);
                moved     = true;
            }

            if (input.keyDown(Key.D))
            {
                movement += xAxis * (MovementSpeed * elapsedTime);
                moved     = true;
            }

            if (moved)
            {
                move(movement);

                MovementSound.play();
            }

            // rotacion
            //

            // invertidos: moverse en x cambia el heading (rotacion sobre y) y viceversa.
            float rotY = input.XposRelative * rotationSpeed;
            float rotX = input.YposRelative * rotationSpeed;

            if (rotY != 0.0f || rotX != 0.0f)
            {
                look(rotX, rotY);
            }

            if (lockMouse)
            {
                Cursor.Position = windowCenter;
            }
        }
Exemplo n.º 17
0
        public void render(float elapsedTime)
        {
            TgcD3dInput d3dInput = GuiController.Instance.D3dInput;
            //Calcular proxima posicion de personaje segun Input
            float  moveForward     = 0f;
            float  rotate          = 0;
            float  jump            = 0;
            bool   moving          = false;
            bool   rotating        = false;
            bool   running         = false;
            bool   jumping         = false;
            string animationAction = "StandBy";

            //obtener velocidades de Modifiers (no deberia estar porque es fijo)
            float velocidadCaminar  = (float)GuiController.Instance.Modifiers.getValue("VelocidadCaminar");
            float velocidadRotacion = (float)GuiController.Instance.Modifiers.getValue("VelocidadRotacion");
            //Obtener boolean para saber si hay que mostrar Bounding Box (tampoco deberia estar)
            bool showBB = (bool)GuiController.Instance.Modifiers.getValue("showBoundingBox");

            //Adelante
            if (d3dInput.keyDown(Key.W))
            {
                moveForward = -velocidadCaminar;
                moving      = true;
            }

            //Atras
            if (d3dInput.keyDown(Key.S))
            {
                moveForward = velocidadCaminar;
                moving      = true;
            }

            //Derecha
            if (d3dInput.keyDown(Key.D))// || d3dInput.XposRelative > 0)
            {
                rotate   = velocidadRotacion;
                rotating = true;
            }

            //Izquierda
            if (d3dInput.keyDown(Key.A))// || d3dInput.XposRelative < 0)
            {
                rotate   = -velocidadRotacion;
                rotating = true;
            }

            //Jump
            if (d3dInput.keyDown(Key.Space))
            {
                jump   = 30;
                moving = true;
            }
            //Run
            if (d3dInput.keyDown(Key.LeftShift))
            {
                running      = true;
                moveForward *= 1.5f;
            }

            if (d3dInput.keyDown(Key.E))
            {
                animationAction = "Talk";
            }

            //Si hubo rotacion
            if (rotating)
            {
                //Rotar personaje y la camara, hay que multiplicarlo por el tiempo transcurrido para no atarse a la velocidad el hardware
                float rotAngle = Geometry.DegreeToRadian(rotate * elapsedTime);
                personaje.rotateY(rotAngle);
                GuiController.Instance.ThirdPersonCamera.rotateY(rotAngle);
            }

            //Si hubo desplazamiento
            if (moving)
            {
                //Activar animacion de caminando
                if (running)
                {
                    personaje.playAnimation("Run", true);
                }
                else if (jumping)
                {
                    personaje.playAnimation("Jump", true);
                }
                else
                {
                    personaje.playAnimation("Walk", true);
                }
            }

            //Si no se esta moviendo, activar animationAction
            else
            {
                personaje.playAnimation(animationAction, true);
            }



            //Vector de movimiento
            Vector3 movementVector = Vector3.Empty;

            if (moving)
            {
                //Aplicar movimiento, desplazarse en base a la rotacion actual del personaje
                movementVector = new Vector3(
                    FastMath.Sin(personaje.Rotation.Y) * moveForward,
                    jump,
                    FastMath.Cos(personaje.Rotation.Y) * moveForward
                    );
            }


            //Actualizar valores de gravedad
            collisionManager.GravityEnabled = (bool)GuiController.Instance.Modifiers["HabilitarGravedad"];
            collisionManager.GravityForce   = (Vector3)GuiController.Instance.Modifiers["Gravedad"];
            collisionManager.SlideFactor    = (float)GuiController.Instance.Modifiers["SlideFactor"];


            //Mover personaje con detección de colisiones, sliding y gravedad
            Vector3 realMovement = collisionManager.moveCharacter(characterSphere, movementVector, objetosColisionables);

            personaje.move(realMovement);

            //Actualizar valores de la linea de movimiento
            directionArrow.PStart = characterSphere.Center;
            directionArrow.PEnd   = characterSphere.Center + Vector3.Multiply(movementVector, 50);
            directionArrow.updateValues();

            //Cargar desplazamiento realizar en UserVar
            GuiController.Instance.UserVars.setValue("Movement", TgcParserUtils.printVector3(realMovement));

            //Render linea
            if (renderDirectionArrow)
            {
                directionArrow.render();
            }


            //Render personaje
            personaje.animateAndRender();
            if (showBB)
            {
                characterSphere.render();
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Renderizar toda la parte cliente, con el manejo de input
        /// </summary>
        private void renderClient()
        {
            //Calcular proxima posicion de personaje segun Input
            float       elapsedTime = GuiController.Instance.ElapsedTime;
            float       moveForward = 0f;
            float       rotate      = 0;
            TgcD3dInput d3dInput    = GuiController.Instance.D3dInput;
            bool        moving      = false;
            bool        rotating    = false;

            //Adelante
            if (d3dInput.keyDown(Key.W))
            {
                moveForward = -VELODICAD_CAMINAR;
                moving      = true;
            }

            //Atras
            if (d3dInput.keyDown(Key.S))
            {
                moveForward = VELODICAD_CAMINAR;
                moving      = true;
            }

            //Derecha
            if (d3dInput.keyDown(Key.D))
            {
                rotate   = VELOCIDAD_ROTACION;
                rotating = true;
            }

            //Izquierda
            if (d3dInput.keyDown(Key.A))
            {
                rotate   = -VELOCIDAD_ROTACION;
                rotating = true;
            }

            //Si hubo rotacion
            if (rotating)
            {
                meshPrincipal.rotateY(Geometry.DegreeToRadian(rotate * elapsedTime));
                GuiController.Instance.ThirdPersonCamera.rotateY(rotate);
            }

            //Si hubo desplazamiento
            if (moving)
            {
                meshPrincipal.moveOrientedY(moveForward * elapsedTime);
            }

            //Hacer que la camara siga al personaje en su nueva posicion
            GuiController.Instance.ThirdPersonCamera.Target = meshPrincipal.Position;


            //Render piso
            piso.render();

            //Renderizar meshPrincipal
            if (meshPrincipal != null)
            {
                meshPrincipal.render();
            }

            //Renderizar otrosMeshes
            foreach (KeyValuePair <int, TgcMesh> entry in otrosMeshes)
            {
                entry.Value.render();
            }
        }
Exemplo n.º 19
0
        public void Update(TgcD3dInput input, TgcMesh monstruo, TgcMesh monstruoSil)
        {
            monstruoMesh    = monstruo;
            monstruoSilueta = monstruoSil;

            dynamicsWorld.StepSimulation(1 / 60f, 100);

            #region Comportamiento

            if (input.keyDown(Key.Space) && ModoCreativo)
            {
                //Activa el comportamiento de la simulacion fisica para la capsula
                personajeBody.ActivationState = ActivationState.ActiveTag;
                personajeBody.AngularVelocity = TGCVector3.Empty.ToBulletVector3();
                personajeBody.ApplyCentralImpulse(strength * 10 * (new TGCVector3(0, 1, 0)).ToBulletVector3());
            }

            if (input.keyDown(Key.W))
            {
                //Activa el comportamiento de la simulacion fisica para la capsula
                personajeBody.ActivationState = ActivationState.ActiveTag;
                personajeBody.AngularVelocity = TGCVector3.Empty.ToBulletVector3();
                personajeBody.ApplyCentralImpulse(-strength * director.ToBulletVector3());
            }
            if (input.keyUp(Key.W))
            {
                personajeBody.ActivationState = ActivationState.IslandSleeping;
            }
            if (input.keyUp(Key.S))
            {
                personajeBody.ActivationState = ActivationState.IslandSleeping;
            }

            if (input.keyDown(Key.S))
            {
                //Activa el comportamiento de la simulacion fisica para la capsula
                personajeBody.ActivationState = ActivationState.ActiveTag;
                personajeBody.AngularVelocity = TGCVector3.Empty.ToBulletVector3();
                personajeBody.ApplyCentralImpulse(strength * director.ToBulletVector3());
            }

            if (input.keyDown(Key.A))
            {
                director.TransformCoordinate(TGCMatrix.RotationY(-angle * rotationStrength));
                personaje.Transform          = TGCMatrix.Translation(TGCVector3.Empty) * TGCMatrix.RotationY(-angle * rotationStrength) * new TGCMatrix(personajeBody.InterpolationWorldTransform);
                personajeBody.WorldTransform = personaje.Transform.ToBsMatrix;
                personaje.RotateY(-angle * rotationStrength);
                personajeActual.RotarManos(-angle * rotationStrength);
                monstruo.RotateY(-angle * rotationStrength);
                monstruoSilueta.RotateY(-angle * rotationStrength);
            }

            if (input.keyDown(Key.D))
            {
                director.TransformCoordinate(TGCMatrix.RotationY(angle * rotationStrength));
                personaje.Transform          = TGCMatrix.Translation(TGCVector3.Empty) * TGCMatrix.RotationY(angle * rotationStrength) * new TGCMatrix(personajeBody.InterpolationWorldTransform);
                personajeBody.WorldTransform = personaje.Transform.ToBsMatrix;
                personaje.RotateY(angle * rotationStrength);
                personajeActual.RotarManos(angle * rotationStrength);
                monstruo.RotateY(angle * rotationStrength);
                monstruoSilueta.RotateY(angle * rotationStrength);
            }


            #endregion Comportamiento
        }