Exemple #1
0
        /// <summary>
        /// Construir caja
        /// </summary>
        public override void doCreation()
        {
            TgcD3dInput input = GuiController.Instance.D3dInput;



            //Si hacen clic con el mouse, ver si hay colision con el suelo
            if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                //Determinar el size en XZ del box
                Vector3 collisionPoint = Control.Grid.getPicking();

                mesh.Position = initSelectionPoint;
                //Configurar BOX
                mesh.Radius = (collisionPoint - initSelectionPoint).Length();
                mesh.updateValues();
            }
            else
            {
                originalRadius = mesh.Radius;
                updateBB();
                //Dejar cargado para que se pueda crear un nuevo sphere
                Control.CurrentState      = MeshCreatorControl.State.CreatePrimitiveSelected;
                Control.CreatingPrimitive = new SpherePrimitive(Control);

                //Agregar sphere a la lista de modelos
                Control.addMesh(this);

                //Seleccionar Box
                Control.SelectionRectangle.clearSelection();
                Control.SelectionRectangle.selectObject(this);
                Control.updateModifyPanel();
            }
        }
Exemple #2
0
        private void Disparar(TgcD3dInput input, float ElapsedTime)
        {
            tiempoDesdeUltimoDisparo += ElapsedTime;
            if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                if (tiempoDesdeUltimoDisparo > tiempoEntreDisparos)
                {
                    tiempoDesdeUltimoDisparo = 0f;
                    VariablesGlobales.managerElementosTemporales.AgregarElemento(new Misil(CalcularPosicionInicialMisil(), coordenadaEsferica, rotation, "Misil\\misil_xwing-TgcScene.xml", Misil.OrigenMisil.XWING));
                    VariablesGlobales.managerSonido.ReproducirSonido(SoundManager.SONIDOS.DISPARO_MISIL_XWING);
                }
            }

            tiempoDesdeUltimaBomba += ElapsedTime;
            if (tiempoDesdeUltimaBomba > tiempoEntreBombas)
            {
                VariablesGlobales.SumarBomba();
            }

            if (input.keyPressed(Key.G))
            {
                if (tiempoDesdeUltimaBomba > tiempoEntreBombas)
                {
                    VariablesGlobales.RestarBomba();
                    tiempoDesdeUltimaBomba = 0f;
                    var bomba = new Bomba(this.GetPosition(), coordenadaEsferica);
                    VariablesGlobales.endgameManager.AgregarBomba(bomba);
                    VariablesGlobales.managerElementosTemporales.AgregarElemento(bomba);
                    VariablesGlobales.managerSonido.ReproducirSonido(SoundManager.SONIDOS.DISPARO_MISIL_XWING);
                }
            }
        }
Exemple #3
0
 private void jugar(EjemploAlumno juego)
 {
     if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
     {
         juego.estado = EstadoDelJuego.Jugando;
     }
 }
        public void Update(float elapsedTime, TgcD3dInput input)
        {
            //Forward
            if (input.keyDown(Key.W))
            {
                moveForward(MovementSpeed * elapsedTime);
            }

            //Backward
            if (input.keyDown(Key.S))
            {
                moveForward(-MovementSpeed * elapsedTime);
            }

            //Strafe right
            if (input.keyDown(Key.D))
            {
                moveSide(MovementSpeed * elapsedTime);
            }

            //Strafe left
            if (input.keyDown(Key.A))
            {
                moveSide(-MovementSpeed * elapsedTime);
            }

            //Jump
            if (input.keyDown(Key.Space))
            {
                moveUp(JumpSpeed * elapsedTime);
            }

            //Crouch
            if (input.keyDown(Key.LeftControl))
            {
                moveUp(-JumpSpeed * elapsedTime);
            }

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

            //Solo rotar si se esta aprentando el boton izq del mouse
            if (lockCam || input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                rotate(-input.XposRelative * RotationSpeed, -input.YposRelative * RotationSpeed);
            }

            if (lockCam)
            {
                Cursor.Position = mouseCenter;
            }

            viewMatrix = TGCMatrix.LookAtLH(eye, target, up);

            updateViewMatrix(D3DDevice.Instance.Device);
        }
        /// <summary>
        /// Construir plano
        /// </summary>
        public override void doCreation()
        {
            TgcD3dInput input = GuiController.Instance.D3dInput;

            //Si hacen clic con el mouse, ver si hay colision con el suelo
            if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                //Obtener altura en Y segun movimient en Y del mouse
                float heightY         = creatingInitMouseY - input.Ypos;
                float adjustedHeightY = MeshCreatorUtils.getMouseIncrementHeightSpeed(Control.Camera, this.BoundingBox, heightY);

                //Determinar posicion X segun la colision con el grid
                Vector3 collisionPoint = Control.Grid.getPicking();
                Vector3 extensionPoint = new Vector3(collisionPoint.X, initSelectionPoint.Y + adjustedHeightY, initSelectionPoint.Z);

                //Obtener maximo y minimo
                Vector3 min = Vector3.Minimize(initSelectionPoint, extensionPoint);
                Vector3 max = Vector3.Maximize(initSelectionPoint, extensionPoint);
                min.Z = initSelectionPoint.Z;
                max.Z = initSelectionPoint.Z + 1;

                //Configurar plano
                mesh.setExtremes(min, max);
                mesh.updateValues();
            }
            //Solto el clic del mouse, generar plano definitivo
            else if (input.buttonUp(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                //Tiene el tamaño minimo tolerado
                Vector3 size = mesh.BoundingBox.calculateSize();
                if (size.X > 1 && size.Y > 1)
                {
                    //Guardar size original del plano para hacer Scaling
                    originalSize = mesh.Size;

                    //Dejar cargado para que se pueda crear un nuevo plano
                    Control.CurrentState      = MeshCreatorControl.State.CreatePrimitiveSelected;
                    Control.CreatingPrimitive = new PlaneXYPrimitive(Control);

                    //Agregar plano a la lista de modelos
                    Control.addMesh(this);

                    //Seleccionar plano
                    Control.SelectionRectangle.clearSelection();
                    Control.SelectionRectangle.selectObject(this);
                    Control.updateModifyPanel();
                }
                //Sino, descartar
                else
                {
                    Control.CurrentState = MeshCreatorControl.State.CreatePrimitiveSelected;
                    mesh.dispose();
                    mesh = null;
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// Estado: seleccionar objetos (estado default)
        /// </summary>
        private void doSelectObject()
        {
            TgcD3dInput input = GuiController.Instance.D3dInput;

            //Si mantiene control y clic con el mouse, iniciar cuadro de seleccion para agregar/quitar a la seleccion actual
            if ((input.keyDown(Microsoft.DirectX.DirectInput.Key.LeftControl) || input.keyDown(Microsoft.DirectX.DirectInput.Key.RightControl)) &&
                input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                currentState                  = State.SelectingObject;
                this.initMousePos             = new Vector2(input.Xpos, input.Ypos);
                this.selectiveObjectsAdditive = true;
            }
            //Si mantiene el clic con el mouse, iniciar cuadro de seleccion
            else if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                currentState                  = State.SelectingObject;
                this.initMousePos             = new Vector2(input.Xpos, input.Ypos);
                this.selectiveObjectsAdditive = false;
            }
        }
Exemple #7
0
        /// <summary>
        /// Construir plano
        /// </summary>
        public override void doCreation()
        {
            TgcD3dInput input = GuiController.Instance.D3dInput;

            //Si hacen clic con el mouse, ver si hay colision con el suelo
            if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                //Determinar el size en XZ del box
                Vector3 collisionPoint = Control.Grid.getPicking();

                //Obtener extremos del rectángulo de selección
                Vector3 min = Vector3.Minimize(initSelectionPoint, collisionPoint);
                Vector3 max = Vector3.Maximize(initSelectionPoint, collisionPoint);
                min.Y = 0;
                max.Y = 1;

                //Configurar plano
                mesh.setExtremes(min, max);
                mesh.updateValues();
            }
            //Solto el clic del mouse, generar plano definitivo
            else if (input.buttonUp(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                //Tiene el tamaño minimo tolerado
                Vector3 size = mesh.BoundingBox.calculateSize();
                if (size.X > 1 && size.Z > 1)
                {
                    //Guardar size original del plano para hacer Scaling
                    originalSize = mesh.Size;

                    //Dejar cargado para que se pueda crear un nuevo plano
                    Control.CurrentState      = MeshCreatorControl.State.CreatePrimitiveSelected;
                    Control.CreatingPrimitive = new PlaneXZPrimitive(Control);

                    //Agregar plano a la lista de modelos
                    Control.addMesh(this);

                    //Seleccionar plano
                    Control.SelectionRectangle.clearSelection();
                    Control.SelectionRectangle.selectObject(this);
                    Control.updateModifyPanel();
                }
                //Sino, descartar
                else
                {
                    Control.CurrentState = MeshCreatorControl.State.CreatePrimitiveSelected;
                    mesh.dispose();
                    mesh = null;
                }
            }
        }
Exemple #8
0
        protected void CheckClicks()
        {
            if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT) && timeSinceLastClick >= clickCooldown)
            {
                TGCVector2 clickPosition = new TGCVector2(input.Xpos, input.Ypos);

                MenuSlot selectedSlot = slots.Find(slot => slot.IsSelected(clickPosition));

                if (selectedSlot != null)
                {
                    selectedSlot.OnClick(owner);
                }
                else
                {
                    Close();
                }

                timeSinceLastClick = 0;
            }
        }
Exemple #9
0
        /// <summary>
        ///     Actualiza los valores de la camara
        /// </summary>
        public override void UpdateCamera(float elapsedTime)
        {
            var heading = 0.0f;
            var pitch   = 0.0f;

            //Obtener direccion segun entrada de teclado
            var direction = getMovementDirection(Input);

            pitch   = Input.YposRelative * RotationSpeed;
            heading = Input.XposRelative * RotationSpeed;

            //Solo rotar si se esta aprentando el boton del mouse configurado
            if (Input.buttonDown(RotateMouseButton))
            {
                rotate(heading, pitch, 0.0f);
            }

            updatePosition(direction, elapsedTime);

            base.SetCamera(eye, direction);
        }
Exemple #10
0
        private void CheckClick()
        {
            bool click = Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT);

            if (click)
            {
                ray.updateRay();
                // me fijo si hubo colision con nave ---> NO SE ESTA USANDO

                /*List<TgcMesh> meshesNave = Nave.Instance().obtenerMeshes();
                 * foreach (TgcMesh mesh in meshesNave)
                 * {
                 *  var aabb = mesh.BoundingBox;
                 *
                 *  var selected = TgcCollisionUtils.intersectRayAABB(ray.Ray, aabb, out collisionPoint);
                 *  if (selected)
                 *  {
                 *          Nave.Instance().Interact();
                 *      break;
                 *  }
                 * }*/

                List <Entity> entities = Entities.GetEntities();
                foreach (Entity entity in entities)
                {
                    var aabb = entity.GetMesh().BoundingBox;

                    var selected = TgcCollisionUtils.intersectRayAABB(ray.Ray, aabb, out collisionPoint);
                    if (selected)
                    {
                        var distance = TGCVector3.Length(entity.Position() - Camara.Position);
                        if (distance <= entity.GetMaxClickDistance())
                        {
                            entity.Interact();
                        }
                        break;
                    }
                }
            }
        }
        /// <summary>
        /// Actualiza los valores de la camara
        /// </summary>
        public void updateCamera()
        {
            //Si la camara no está habilitada, no procesar el resto del input
            if (!enable)
            {
                return;
            }

            float       elapsedTimeSec = GuiController.Instance.ElapsedTime;
            TgcD3dInput d3dInput       = GuiController.Instance.D3dInput;

            //Imprimir por consola la posicion actual de la camara
            if ((d3dInput.keyDown(Key.LeftShift) || d3dInput.keyDown(Key.RightShift)) && d3dInput.keyPressed(Key.P))
            {
                GuiController.Instance.Logger.logVector3(getPosition());
                return;
            }


            float heading = 0.0f;
            float pitch   = 0.0f;

            //Obtener direccion segun entrada de teclado
            Vector3 direction = getMovementDirection(d3dInput);

            pitch   = d3dInput.YposRelative * rotationSpeed;
            heading = d3dInput.XposRelative * rotationSpeed;

            //Solo rotar si se esta aprentando el boton del mouse configurado
            if (d3dInput.buttonDown(rotateMouseButton))
            {
                rotate(heading, pitch, 0.0f);
            }


            updatePosition(direction, elapsedTimeSec);
        }
Exemple #12
0
        private void coordenadasMouse() //se fija si hace clic sobre un boton
        {
            TgcD3dInput d3dInput = GuiController.Instance.D3dInput;
            //Obtener variacion XY del mouse
            float mouseX = 0f;
            float mouseY = 0f;
            float botonX = boton1.Position.X + boton1.Texture.Width;
            float botonY = boton1.Position.Y + boton1.Texture.Height;

            float boton2X = boton2.Position.X + boton2.Texture.Width;
            float boton2Y = boton2.Position.Y + boton2.Texture.Height;

            if (d3dInput.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                mouseX = d3dInput.Xpos; // XposRelative;
                mouseY = d3dInput.Ypos; // YposRelative;

                if ((mouseX > boton1.Position.X) && (mouseX < botonX) && (mouseY > boton1.Position.Y) && (mouseY < botonY))
                {
                    oceano.rayo = true;
                    //MessageBox.Show("CLIC EN SPRITE CUADRADO DERECHO");
                }
                if ((mouseX > boton2.Position.X) && (mouseX < boton2X) && (mouseY > boton2.Position.Y) && (mouseY < boton2Y))
                {
                    traslacion = -150;
                    //Crear Sprite animado para la gaviota
                    animatedSprite2 = new TgcAnimatedSprite(
                        GuiController.Instance.AlumnoEjemplosMediaDir + "RenderGroup\\texturas\\gaviotas2.png", //Textura de 1024 X 1024
                        new Size(256, 256),                                                                     //Tamaño de un frame (128x128px en este caso)
                        16,                                                                                     //Cantidad de frames, (son 16 de 128x128px)
                        1                                                                                       //Velocidad de animacion, en cuadros x segundo
                        );
                    //MessageBox.Show("CLIC EN SPRITE CUADRADO IZQUIERDO");
                }
            }
        }
Exemple #13
0
        /// <summary>
        /// Manejar eventos de Input
        /// </summary>
        private void handleInput()
        {
            TgcD3dInput input = GuiController.Instance.D3dInput;

            //Seleccionar modelo
            if (currentState == GuiState.SelectionMode)
            {
                //Picking con mouse Izquierdo
                if (input.buttonPressed(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    findSelectedMeshWithPicking();
                }
            }
            //Trasladar modelo seleccionado
            else if (currentState == GuiState.TranslateMode)
            {
                if (selectedMeshList.Count > 0)
                {
                    //Comenzar a trasladar
                    if (input.buttonPressed(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                    {
                        initGizmoDragging();
                    }
                    //Arrastrando gizmo
                    else if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                    {
                        doGizmoTranslate();
                    }
                    //Terminar el traslado
                    else if (input.buttonUp(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                    {
                        endGizmoDragging();
                    }
                }
            }
        }
Exemple #14
0
        public override void update()
        {
            TgcD3dInput input = GuiController.Instance.D3dInput;

            switch (currentState)
            {
            case State.Init:

                selectedAxis = Axis.None;

                //Iniciar seleccion de eje
                if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    Control.PickingRay.updateRay();
                    Vector3 collP;

                    //Buscar colision con eje con Picking
                    if (TgcCollisionUtils.intersectRayAABB(Control.PickingRay.Ray, boxX.BoundingBox, out collP))
                    {
                        selectedAxis = Axis.X;
                    }
                    else if (TgcCollisionUtils.intersectRayAABB(Control.PickingRay.Ray, boxY.BoundingBox, out collP))
                    {
                        selectedAxis = Axis.Y;
                    }
                    else if (TgcCollisionUtils.intersectRayAABB(Control.PickingRay.Ray, boxZ.BoundingBox, out collP))
                    {
                        selectedAxis = Axis.Z;
                    }
                    else
                    {
                        selectedAxis = Axis.None;
                    }

                    //Si eligio un eje, iniciar dragging
                    if (selectedAxis != Axis.None)
                    {
                        currentState = State.Dragging;
                        initMouseP   = new Vector2(input.XposRelative, input.YposRelative);
                    }
                    else
                    {
                        if (input.buttonPressed(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                        {
                            bool additive = input.keyDown(Microsoft.DirectX.DirectInput.Key.LeftControl) || input.keyDown(Microsoft.DirectX.DirectInput.Key.RightControl);
                            Control.CurrentState = MeshCreatorControl.State.SelectObject;
                            Control.SelectionRectangle.doDirectSelection(additive);
                        }
                    }
                }
                //Hacer mouse over sobre los ejes
                else
                {
                    Control.PickingRay.updateRay();
                    Vector3 collP;

                    //Buscar colision con eje con Picking
                    if (TgcCollisionUtils.intersectRayAABB(Control.PickingRay.Ray, boxX.BoundingBox, out collP))
                    {
                        selectedAxis = Axis.X;
                    }
                    else if (TgcCollisionUtils.intersectRayAABB(Control.PickingRay.Ray, boxY.BoundingBox, out collP))
                    {
                        selectedAxis = Axis.Y;
                    }
                    else if (TgcCollisionUtils.intersectRayAABB(Control.PickingRay.Ray, boxZ.BoundingBox, out collP))
                    {
                        selectedAxis = Axis.Z;
                    }
                    else
                    {
                        selectedAxis = Axis.None;
                    }
                }

                break;

            case State.Dragging:

                //Mover
                if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    //Obtener vector 2D de movimiento relativo del mouse
                    Vector2 mouseScreenVec = new Vector2(input.XposRelative, input.YposRelative);
                    //mouseScreenVec.Normalize();

                    //Projectar vector 2D del eje elegido
                    TgcBox  currentAxisBox = getAxisBox(selectedAxis);
                    Vector2 axisScreenVec  = MeshCreatorUtils.projectAABBScreenVec(currentAxisBox.BoundingBox);

                    //Hacer DOT product entre ambos vectores para obtener la contribucion del mouse en esa direccion
                    float scaling = Vector2.Dot(axisScreenVec, mouseScreenVec);
                    scaling = MeshCreatorUtils.getMouseScaleIncrementSpeed(Control.Camera, currentAxisBox.BoundingBox, scaling);
                    Vector3 currentScale = new Vector3(0, 0, 0);

                    //Escala en eje X
                    if (selectedAxis == Axis.X)
                    {
                        currentScale.X = scaling;
                    }
                    //Escala en eje Y
                    else if (selectedAxis == Axis.Y)
                    {
                        currentScale.Y = scaling;
                    }
                    //Escala en eje Z
                    else if (selectedAxis == Axis.Z)
                    {
                        currentScale.Z = scaling;
                    }


                    //Escalar objetos
                    foreach (EditorPrimitive p in Control.SelectionList)
                    {
                        //Agregar scaling, controlando que no sea menor a cero
                        Vector3 scale  = p.Scale;
                        Vector3 oldMin = p.BoundingBox.PMin;

                        scale  += currentScale;
                        scale.X = scale.X < 0.01f ? 0.01f : scale.X;
                        scale.Y = scale.Y < 0.01f ? 0.01f : scale.Y;
                        scale.Z = scale.Z < 0.01f ? 0.01f : scale.Z;

                        p.Scale = scale;

                        //Si se escala para una sola direccion hay que desplazar el objeto
                        if (!Control.ScaleBothDirections)
                        {
                            p.move(oldMin - p.BoundingBox.PMin);
                        }
                    }

                    //TODO: Hay que ir estirando los ejes a medida que se agranda la escala

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

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


                break;
            }



            //Ajustar tamaño de ejes
            setAxisPositionAndSize();
        }
Exemple #15
0
        /// <summary>
        /// Estado: Cuando se esta arrastrando el mouse para armar el cuadro de seleccion
        /// </summary>
        private void doSelectingObject()
        {
            TgcD3dInput input = GuiController.Instance.D3dInput;

            //Mantiene el mouse apretado
            if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                //Definir recuadro
                Vector2 mousePos = new Vector2(input.Xpos, input.Ypos);
                Vector2 min      = Vector2.Minimize(initMousePos, mousePos);
                Vector2 max      = Vector2.Maximize(initMousePos, mousePos);

                rectMesh.updateMesh(min, max);
            }
            //Solo el mouse
            else if (input.buttonUp(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                //Definir recuadro
                Vector2   mousePos = new Vector2(input.Xpos, input.Ypos);
                Vector2   min      = Vector2.Minimize(initMousePos, mousePos);
                Vector2   max      = Vector2.Maximize(initMousePos, mousePos);
                Rectangle r        = new Rectangle((int)min.X, (int)min.Y, (int)(max.X - min.X), (int)(max.Y - min.Y));

                //Usar recuadro de seleccion solo si tiene un tamaño minimo
                if (r.Width > 1 && r.Height > 1)
                {
                    //Limpiar seleccionar anterior si no estamos agregando en forma aditiva
                    if (!selectiveObjectsAdditive)
                    {
                        clearSelection();
                    }

                    //Buscar que primitivas caen dentro de la seleccion y elegirlos
                    int i = 0;
                    EditPolyPrimitive p = iteratePrimitive(currentPrimitive, i);
                    while (p != null)
                    {
                        //Ver si hay colision contra la proyeccion de la primitiva y el rectangulo 2D
                        Rectangle primRect;
                        if (p.projectToScreen(mesh.Transform, out primRect))
                        {
                            if (r.IntersectsWith(primRect))
                            {
                                //Agregar el objeto en forma aditiva
                                if (selectiveObjectsAdditive)
                                {
                                    selectOrRemovePrimitiveIfPresent(p);
                                }
                                //Agregar el objeto en forma simple
                                else
                                {
                                    selectPrimitive(p);
                                }
                            }
                        }
                        p = iteratePrimitive(currentPrimitive, ++i);
                    }
                }
                //Si el recuadro no tiene tamaño suficiente, hacer seleccion directa
                else
                {
                    doDirectSelection(selectiveObjectsAdditive);
                }

                currentState = State.SelectObject;

                /*
                 * //Si quedo algo seleccionado activar gizmo
                 * if (selectionList.Count > 0)
                 * {
                 *  activateTranslateGizmo();
                 * }
                 */

                //Actualizar panel de Modify con lo que se haya seleccionado, o lo que no
                updateUiPanel();
            }



            //Dibujar recuadro
            rectMesh.render();
        }
        /// <summary>
        ///     Actualiza los valores de la camara.
        /// </summary>
        public override void UpdateCamera(float elapsedTime)
        {
            //Obtener variacion XY del mouse
            var mouseX = 0f;
            var mouseY = 0f;

            if (Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                mouseX = Input.XposRelative;
                mouseY = Input.YposRelative;

                DiffX += mouseX * elapsedTime * RotationSpeed;
                DiffY += mouseY * elapsedTime * RotationSpeed;
            }
            else
            {
                DiffX += mouseX;
                DiffY += mouseY;
            }

            //Calcular rotacion a aplicar
            var rotX = -DiffY / FastMath.PI;
            var rotY = DiffX / FastMath.PI;

            //Truncar valores de rotacion fuera de rango
            if (rotX > FastMath.PI * 2 || rotX < -FastMath.PI * 2)
            {
                DiffY = 0;
                rotX  = 0;
            }

            //Invertir Y de UpVector segun el angulo de rotacion
            if (rotX < -FastMath.PI / 2 && rotX > -FastMath.PI * 3 / 2)
            {
                UpVector = DEFAULT_DOWN;
            }
            else if (rotX > FastMath.PI / 2 && rotX < FastMath.PI * 3 / 2)
            {
                UpVector = DEFAULT_DOWN;
            }
            else
            {
                UpVector = DEFAULT_UP_VECTOR;
            }

            //Determinar distancia de la camara o zoom segun el Mouse Wheel
            if (Input.WheelPos != 0)
            {
                DiffZ += ZoomFactor * Input.WheelPos * -1;
            }
            var distance = -CameraDistance * DiffZ;

            //Limitar el zoom a 0
            if (distance > 0)
            {
                distance = 0;
            }

            //Realizar Transformacion: primero alejarse en Z, despues rotar en X e Y y despues ir al centro de la cmara
            var m = TGCMatrix.Translation(0, 0, -distance)
                    * TGCMatrix.RotationX(rotX)
                    * TGCMatrix.RotationY(rotY)
                    * TGCMatrix.Translation(CameraCenter);

            //Extraer la posicion final de la matriz de transformacion
            NextPos = new TGCVector3(m.M41, m.M42, m.M43);

            //Hacer efecto de Pan View
            if (Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_RIGHT))
            {
                var dx           = -Input.XposRelative;
                var dy           = Input.YposRelative;
                var panSpeedZoom = PanSpeed * FastMath.Abs(distance);

                var d = CameraCenter - NextPos;
                d.Normalize();

                var n = TGCVector3.Cross(d, UpVector);
                n.Normalize();

                var up   = TGCVector3.Cross(n, d);
                var desf = TGCVector3.Scale(up, dy * panSpeedZoom) - TGCVector3.Scale(n, dx * panSpeedZoom);
                NextPos      = NextPos + desf;
                CameraCenter = CameraCenter + desf;
            }

            //asigna las posiciones de la camara.
            base.SetCamera(NextPos, CameraCenter, UpVector);
        }
        public void render(float elapsedTime)
        {
            TgcD3dInput d3dInput = GuiController.Instance.D3dInput;
            //Calcular proxima posicion de personaje segun Input
            float     moveForward     = 0f;
            float     moveSide        = 0f;
            float     rotateY         = 0;
            float     rotateX         = 0;
            float     jump            = 0;
            bool      moving          = false;
            bool      rotating        = false;
            bool      rotatingY       = false;
            bool      rotatingX       = false;
            bool      running         = false;
            bool      jumping         = false;
            string    animationAction = "StandBy";
            TgcSprite mira;

            //Crear Sprite de mira
            mira         = new TgcSprite();
            mira.Texture = TgcTexture.createTexture(GuiController.Instance.AlumnoEjemplosMediaDir + "\\Kamikaze3D\\mira.png");

            //Ubicarlo centrado en la pantalla
            Size screenSize  = GuiController.Instance.Panel3d.Size;
            Size textureSize = mira.Texture.Size;

            mira.Position = new Vector2(screenSize.Width / 2 - textureSize.Width / 2, screenSize.Height / 2 - textureSize.Height / 2);

            TgcText2d hitCantTextY = new TgcText2d();

            hitCantTextY.Position = new Point(0, 0);
            hitCantTextY.Color    = Color.White;

            TgcText2d hitCantTextX = new TgcText2d();

            hitCantTextX.Position = new Point(0, 20);
            hitCantTextX.Color    = Color.White;

            //obtener velocidades de Modifiers (no deberia estar porque es fijo)
            float velocidadCaminar = (float)GuiController.Instance.Modifiers.getValue("VelocidadCaminar");
            //float velocidadMoveSide = (float)GuiController.Instance.Modifiers.getValue("velocidadMoveSide");
            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.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT) && d3dInput.XposRelative > 0)
            {
                if (camara.RotationY < (Math.PI))
                {
                    rotateY   = velocidadRotacion;
                    rotating  = true;
                    rotatingY = true;
                }
            }

            //Mover Derecha
            if (d3dInput.keyDown(Key.D))
            {
                moveSide = -velocidadCaminar;
                moving   = true;
            }

            //Izquierda
            if (d3dInput.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT) && d3dInput.XposRelative < 0)
            {
                if (camara.RotationY > -(Math.PI))
                {
                    rotateY   = -velocidadRotacion;
                    rotating  = true;
                    rotatingY = true;
                }
            }

            //Mover Izquierda
            if (d3dInput.keyDown(Key.A))
            {
                moveSide = velocidadCaminar;
                moving   = true;
            }

            //Arriba
            if (d3dInput.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT) && d3dInput.YposRelative < 0)
            {
                if (camara.RotationX > -(Math.PI / 3))
                {
                    rotateX   = -velocidadRotacion;
                    rotating  = true;
                    rotatingX = true;
                }
            }

            //Abajo
            if (d3dInput.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT) && d3dInput.YposRelative > 0)
            {
                if (camara.RotationX < (Math.PI / 3))
                {
                    rotateX   = velocidadRotacion;
                    rotating  = true;
                    rotatingX = 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 = "WeaponPos";
            }

            //Si hubo rotacion
            if (rotating)
            {
                if (rotatingY)
                {
                    //Rotar personaje y la camara, hay que multiplicarlo por el tiempo transcurrido para no atarse a la velocidad el hardware

                    float rotAngleY = Geometry.DegreeToRadian(rotateY * elapsedTime);
                    personaje.rotateY(rotAngleY);
                    camara.rotateY(rotAngleY);
                }
                if (rotatingX)
                {
                    //Rotar personaje y la camara, hay que multiplicarlo por el tiempo transcurrido para no atarse a la velocidad el hardware
                    float rotAngleX = Geometry.DegreeToRadian(rotateX * elapsedTime);
                    camara.rotateX(rotAngleX);
                }
            }


            //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
                //Grupo Kamikaze3D :: Se agrega también al desplazamiento sobre el eje x y eje z, el valor de desplazamiento lateral
                movementVector = new Vector3(
                    (FastMath.Sin(personaje.Rotation.Y) * moveForward) + (FastMath.Cos(personaje.Rotation.Y) * moveSide),
                    jump,
                    (FastMath.Cos(personaje.Rotation.Y) * moveForward) + (-FastMath.Sin(personaje.Rotation.Y) * moveSide)
                    );
            }


            //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();

            /* //Iniciar dibujado de todos los Sprites de la escena (en este caso es solo uno)
             * GuiController.Instance.Drawer2D.beginDrawSprite();
             *
             * //Dibujar sprite (si hubiese mas, deberian ir todos aquí)
             * mira.render();
             *
             * //Finalizar el dibujado de Sprites
             * GuiController.Instance.Drawer2D.endDrawSprite();*/

            hitCantTextY.Text = "Y: " + camara.RotationY;
            hitCantTextX.Text = "X: " + camara.RotationX;
            hitCantTextY.render();
            hitCantTextX.render();

            if (showBB)
            {
                characterSphere.render();
            }
        }
Exemple #18
0
        public void actualizar(Vector3 pos)
        {
            if (input.keyPressed(Key.P))
            {
                if (!apuntando)
                {
                    apuntando            = true;
                    apuntado             = new Vector3(0, 50, -50);
                    camera.OffsetForward = DISTANCIA_APUNTANDO;
                    camera.OffsetHeight  = ALTURA_APUNTANDO;
                }
                else
                {
                    apuntando = false;
                    apuntado  = new Vector3(0, 0, 0);

                    camera.setCamera(pos, ALTURA, DISTANCIA);
                }
            }
            if (apuntando)
            {
                camera.RotationY = ship.anguloRotacion;
            }
            //Solo rotar si se esta aprentando el boton izq del mouse
            if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                if (!apuntando)
                {
                    camera.rotateY(-input.XposRelative * ROTATION_SPEED);
                }
            }

            if (input.keyDown(Key.LeftShift))
            {
                camera.OffsetHeight  += 5;
                camera.OffsetForward += 5;
            }

            if (input.keyDown(Key.LeftControl))
            {
                camera.OffsetHeight  -= 5;
                camera.OffsetForward -= 5;
            }

            if (input.WheelPos != wheelPos)
            {
                zoom = input.WheelPos - wheelPos < 0 ? 20f : -20F;
                camera.OffsetHeight  += zoom;
                camera.OffsetForward += zoom;
            }


            Vector3 aux = ship.delante;

            aux.Y         = 0;
            camera.Target = pos + new Vector3(0, apuntado.Y, 0) + (apuntado.Z * aux);



            camera.updateCamera();
        }
        public void Update(TgcD3dInput Input)
        {
            if (!activo)
            {
                return;
            }

            #region manejarInput
            var moveVector = TGCVector3.Empty;

            //Forward
            if (Input.keyDown(Key.W))
            {
                moveVector += new TGCVector3(0, 0, -1) * MovementSpeed;
            }
            //Backward
            if (Input.keyDown(Key.S))
            {
                moveVector += new TGCVector3(0, 0, 1) * MovementSpeed;
            }
            //Strafe right
            if (Input.keyDown(Key.D))
            {
                moveVector += new TGCVector3(-1, 0, 0) * MovementSpeed;
            }
            //Strafe left
            if (Input.keyDown(Key.A))
            {
                moveVector += new TGCVector3(1, 0, 0) * MovementSpeed;
            }

            //Solo rotar si se esta aprentando el boton izq del mouse
            if (Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                leftrightRot          -= -Input.XposRelative * RotationSpeed;
                camaraInterna.rotacion = TGCMatrix.RotationY(leftrightRot);
            }
            #endregion

            #region manejarAltura

            int x = (int)(zombie.Position.X / 255f);
            int z = (int)(zombie.Position.Z / 255f);
            int y = alturaEnPunto(x, z);

            if (y != -1)
            {
                zombie.Position = zombie.Position + moveVector;
                zombie.Position = new TGCVector3(zombie.Position.X, y + 30, zombie.Position.Z);
                //body.Translate(zombie.Position.ToBsVector);
            }
            else
            {
                if (z < 0)
                {
                    z = 0;
                }
                if (z > 63)
                {
                    z = 63;
                }
                if (x < 0)
                {
                    x = 0;
                }
                if (x > 63)
                {
                    x = 63;
                }
                zombie.Position = new TGCVector3(x, zombie.Position.Y, z);
            }
            #endregion

            camaraInterna.Target = zombie.Position;
        }
Exemple #20
0
        public void render(float elapsedTime)
        {
            TgcD3dInput d3dInput = GuiController.Instance.D3dInput;
            //Calcular proxima posicion de personaje segun Input
            float moveForward = 0f;
            float moveSide    = 0f;
            float rotateY     = 0;
            //float rotateX = 0;
            float jump      = 0;
            bool  moving    = false;
            bool  rotating  = false;
            bool  rotatingY = false;
            // bool rotatingX = false;
            bool   running         = false;
            bool   jumping         = false;
            string animationAction = "StandBy";

            //Ubicarlo centrado en la pantalla
            Size screenSize  = GuiController.Instance.Panel3d.Size;
            Size textureSize = mira.Texture.Size;

            mira.Enabled = false;

            TgcText2d hitCantTextY = new TgcText2d();

            hitCantTextY.Position = new Point(0, 0);
            hitCantTextY.Color    = Color.White;

            /*  TgcText2d hitCantTextX = new TgcText2d();
             * hitCantTextX.Position = new Point(0, 20);
             * hitCantTextX.Color = Color.White;
             */
            if (destroy)
            {
                goto Rendering;
            }

            //obtener velocidades de Modifiers
            float velocidadCaminar  = (float)GuiController.Instance.Modifiers["VelocidadCaminar"];
            float velocidadRotacion = (float)GuiController.Instance.Modifiers.getValue("VelocidadRotacion");

            //Detonar
            if (this.canExplode && d3dInput.keyDown(Key.K))
            {
                animationAction = "Talk";
                this.explosion.detonar();
                destroy = true;
            }

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


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

            //Derecha
            if (d3dInput.XposRelative > 0 || d3dInput.keyDown(Key.RightArrow))
            {
                if (d3dInput.XposRelative > 0)
                {
                    rotateY = (velocidadRotacion / 2);
                }
                else
                {
                    rotateY = velocidadRotacion;
                }

                rotating  = true;
                rotatingY = true;
            }

            //Izquierda
            if (d3dInput.XposRelative < 0 || d3dInput.keyDown(Key.LeftArrow))
            {
                if (d3dInput.XposRelative < 0)
                {
                    rotateY = -(velocidadRotacion / 2);
                }
                else
                {
                    rotateY = -velocidadRotacion;
                }

                rotating  = true;
                rotatingY = true;
            }

            //Mover Derecha
            if (d3dInput.keyDown(Key.D))
            {
                if (!moving)
                {
                    moveSide = -velocidadCaminar;
                }
                else
                {
                    moveSide = -velocidadCaminar / 2;
                }
                moving = true;
            }


            //Mover Izquierda
            if (d3dInput.keyDown(Key.A))
            {
                if (!moving)
                {
                    moveSide = velocidadCaminar;
                }
                else
                {
                    moveSide = velocidadCaminar / 2;
                }
                moving = true;
            }

/*            //Arriba
 *          if (d3dInput.YposRelative < 0)
 *          {
 *              //if (camara.RotationX > -(Math.PI / 3))
 *              //{
 *                  rotateX = -velocidadRotacion;
 *                  rotating = true;
 *                  rotatingX = true;
 *              //}
 *          }
 *
 *          //Abajo
 *          if (d3dInput.YposRelative > 0)
 *          {
 *              //if (camara.RotationX < (Math.PI / 3))
 *              //{
 *                  rotateX = velocidadRotacion;
 *                  rotating = true;
 *                  rotatingX = 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) || d3dInput.buttonDown(TgcD3dInput.MouseButtons.BUTTON_RIGHT))
            {
                mira.Enabled    = true;
                animationAction = "WeaponPos";
                if (d3dInput.buttonPressed(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    this.fire();
                }
            }

            //Si hubo rotacion
            if (rotating)
            {
                if (rotatingY)
                {
                    //Rotar personaje y la camara, hay que multiplicarlo por el tiempo transcurrido para no atarse a la velocidad el hardware

                    float rotAngleY = Geometry.DegreeToRadian(rotateY * elapsedTime);
                    this.personaje.rotateY(rotAngleY);
                    this.camara.rotateY(rotAngleY);
                }

                /*  if (rotatingX)
                 * {
                 *  //Rotar personaje y la camara, hay que multiplicarlo por el tiempo transcurrido para no atarse a la velocidad el hardware
                 *  float rotAngleX = Geometry.DegreeToRadian(rotateX * elapsedTime);
                 *  this.camara.rotateX(rotAngleX);
                 *
                 * }*/
            }


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

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

            if (life <= 0)
            {
                this.personaje.playAnimation("Muerte", true);
            }


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

            if (moving)
            {
                //Aplicar movimiento, desplazarse en base a la rotacion actual del personaje
                //Grupo Kamikaze3D :: Se agrega también al desplazamiento sobre el eje x y eje z, el valor de desplazamiento lateral
                movementVector = new Vector3(
                    (FastMath.Sin(this.personaje.Rotation.Y) * moveForward) + (FastMath.Cos(this.personaje.Rotation.Y) * moveSide),
                    jump,
                    (FastMath.Cos(this.personaje.Rotation.Y) * moveForward) + (-FastMath.Sin(this.personaje.Rotation.Y) * moveSide)
                    );
            }


            //Mover personaje con detección de colisiones, sliding y gravedad
            Vector3 realMovement;

            if (collisionWithCharacters(movementVector))
            {
                realMovement = Vector3.Empty;
            }
            else
            {
                realMovement = collisionManager.moveCharacter(this.characterSphere, movementVector, this.objetosColisionables);
            }
            this.personaje.move(realMovement);

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

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

Rendering:

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

            this.renderBullets();
            //Render personaje
            this.personaje.animateAndRender();

            //Iniciar dibujado de todos los Sprites de la escena (en este caso es solo uno)
            GuiController.Instance.Drawer2D.beginDrawSprite();

            //Dibujar sprite (si hubiese mas, deberian ir todos aquí)
            mira.render();

            //Finalizar el dibujado de Sprites
            GuiController.Instance.Drawer2D.endDrawSprite();

            //hitCantTextY.Text = "Y: " + camara.RotationY;
            //hitCantTextX.Text = "X: " + camara.RotationX;
            //hitCantTextY.render();
            //hitCantTextX.render();
        }
Exemple #21
0
        public override void update()
        {
            TgcD3dInput input = GuiController.Instance.D3dInput;

            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
                    Control.PickingRay.updateRay();
                    gizmoMesh.selectAxisByPicking(Control.PickingRay.Ray);
                    if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.X)
                    {
                        initMouseP3d = Control.Grid.getPickingX(Control.PickingRay.Ray, gizmoMesh.GizmoCenter);
                    }
                    else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.Y)
                    {
                        initMouseP3d = Control.Grid.getPickingY(Control.PickingRay.Ray, gizmoMesh.GizmoCenter);
                    }
                    else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.Z)
                    {
                        initMouseP3d = Control.Grid.getPickingZ(Control.PickingRay.Ray, gizmoMesh.GizmoCenter);
                    }
                    else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.XZ)
                    {
                        initMouseP3d = Control.Grid.getPickingXZ(Control.PickingRay.Ray, gizmoMesh.GizmoCenter);
                    }
                    else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.XY)
                    {
                        initMouseP3d = Control.Grid.getPickingXY(Control.PickingRay.Ray, gizmoMesh.GizmoCenter);
                    }
                    else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.YZ)
                    {
                        initMouseP3d = Control.Grid.getPickingYZ(Control.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);
                            Control.CurrentState = MeshCreatorControl.State.SelectObject;
                            Control.SelectionRectangle.doDirectSelection(additive);
                        }
                    }
                }
                //Hacer mouse over sobre los ejes
                else
                {
                    //Buscar colision con eje con Picking
                    Control.PickingRay.updateRay();
                    gizmoMesh.selectAxisByPicking(Control.PickingRay.Ray);
                }

                break;

            case State.Dragging:

                //Mover
                if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    Control.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   = Control.Grid.getPickingX(Control.PickingRay.Ray, gizmoMesh.GizmoCenter);
                            currentMove.X = endMouseP3d.X - initMouseP3d.X;
                        }
                        //Desplazamiento en eje Y
                        else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.Y)
                        {
                            endMouseP3d   = Control.Grid.getPickingY(Control.PickingRay.Ray, gizmoMesh.GizmoCenter);
                            currentMove.Y = endMouseP3d.Y - initMouseP3d.Y;
                        }
                        //Desplazamiento en eje Z
                        else if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.Z)
                        {
                            endMouseP3d   = Control.Grid.getPickingZ(Control.PickingRay.Ray, gizmoMesh.GizmoCenter);
                            currentMove.Z = endMouseP3d.Z - initMouseP3d.Z;
                        }
                    }
                    //Desplazamiento en dos ejes
                    else
                    {
                        //Plano XZ
                        if (gizmoMesh.SelectedAxis == TranslateGizmoMesh.Axis.XZ)
                        {
                            endMouseP3d   = Control.Grid.getPickingXZ(Control.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   = Control.Grid.getPickingXY(Control.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   = Control.Grid.getPickingYZ(Control.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 (Control.SnapToGridEnabled)
                    {
                        snapMovementToGrid(ref currentMove.X, ref acumMovement.X, Control.SnapToGridCellSize);
                        snapMovementToGrid(ref currentMove.Y, ref acumMovement.Y, Control.SnapToGridCellSize);
                        snapMovementToGrid(ref currentMove.Z, ref acumMovement.Z, Control.SnapToGridCellSize);
                    }

                    //Mover objetos
                    foreach (EditorPrimitive p in Control.SelectionList)
                    {
                        p.move(currentMove);
                    }

                    //Mover ejes
                    gizmoMesh.moveGizmo(currentMove);

                    //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, Control.Camera);
        }
Exemple #22
0
        public void update(float elapsedTime)
        {
            TgcD3dInput d3dInput = GuiController.Instance.D3dInput;

            if (d3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.F1))
            {
                paused = !paused;
            }

            if (paused)
            {
                return;
            }

            if (d3dInput.keyPressed(Microsoft.DirectX.DirectInput.Key.M))
            {
                mouseCaptured = !mouseCaptured;
                if (mouseCaptured)
                {
                    Cursor.Hide();
                }
                else
                {
                    Cursor.Show();
                }
            }

            vel += d3dInput.WheelPos * acel_mouse_wheel;

            if (mouseCaptured && d3dInput.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                //float pitch = d3dInput.YposRelative * rotationSpeed;
                float heading = d3dInput.XposRelative * rotationSpeed;
                dir = rotar_xz(dir, -heading);
            }

            if (mouseCaptured)
            {
                Cursor.Position = mouseCenter;
            }


            // aplico la velocidad
            pos = pos + dir * vel * elapsedTime;

            // verifico si sigue en la ruta
            float H = circuito.updatePos(pos.X, pos.Z);

            if (!circuito.en_ruta)
            {
                // lo mando de nuevo a la ruta
                pos = circuito.que_pos_buena(pos.X, pos.Z);
            }

            // mantengo el auto en la ruta
            pos.Y = H;

            // actualizo la posiicon del auto
            car.Position  = pos;
            car.Transform = CalcularMatriz(pos, car_Scale, -dir);

            // actualizo la camara
            GuiController.Instance.FpsCamera.setCamera(pos - dir * dist_cam + desf, pos + desf);
            //GuiController.Instance.FpsCamera.setCamera(new Vector3(500, 4000, 500), new Vector3(0, 0, 0));
            GuiController.Instance.FpsCamera.updateCamera();
        }
        public unsafe override void Render()
        {
            Device device = GuiController.Instance.D3dDevice;

            time += ElapsedTime;
            TgcD3dInput d3dInput = GuiController.Instance.D3dInput;

            //Obtener variacion XY del mouse
            if (d3dInput.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                float mouseX = d3dInput.XposRelative;
                float mouseY = d3dInput.YposRelative;
                float an     = mouseX * 0.1f;

                float x = (float)(LookFrom.X * Math.Cos(an) + LookFrom.Z * Math.Sin(an));
                float z = (float)(LookFrom.Z * Math.Cos(an) - LookFrom.X * Math.Sin(an));
                LookFrom.X  = x;
                LookFrom.Z  = z;
                LookFrom.Y += mouseY * 150f;
            }

            //Determinar distancia de la camara o zoom segun el Mouse Wheel
            if (d3dInput.WheelPos != 0)
            {
                TGCVector3 vdir = LookFrom - LookAt;
                vdir.Normalize();
                LookFrom = LookFrom - vdir * (d3dInput.WheelPos * 500);
            }

            device.Transform.View = TGCMatrix.LookAtLH(LookFrom, LookAt, new TGCVector3(0, 1, 0));

            TGCMatrix ant_Proj  = device.Transform.Projection;
            TGCMatrix ant_World = device.Transform.World;
            TGCMatrix ant_View  = device.Transform.View;

            device.Transform.Projection = TGCMatrix.Identity;
            device.Transform.World      = TGCMatrix.Identity;
            device.Transform.View       = TGCMatrix.Identity;
            device.SetRenderState(RenderStates.AlphaBlendEnable, false);

            // rt1= velocidad
            Surface pOldRT = device.GetRenderTarget(0);
            Surface pSurf  = g_pVelocidadOut.GetSurfaceLevel(0);

            device.SetRenderTarget(0, pSurf);
            Surface pOldDS = device.DepthStencilSurface;

            device.DepthStencilSurface = g_pDepthStencil;
            // rt2 = posicion
            Surface pSurf2 = g_pPosOut.GetSurfaceLevel(0);

            device.SetRenderTarget(1, pSurf2);

            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
            device.BeginScene();

            effect.SetValue("elapsedTime", ElapsedTime);
            effect.Technique = "ComputeVel";
            effect.SetValue("g_pVelocidad", g_pVelocidad);
            effect.SetValue("g_pPos", g_pPos);
            device.VertexFormat = CustomVertex.PositionTextured.Format;
            device.SetStreamSource(0, g_pVBV3D, 0);
            effect.Begin(FX.None);
            effect.BeginPass(1);
            device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);
            effect.EndPass();
            effect.End();
            device.EndScene();

            // leo los datos de la textura de velocidades
            // ----------------------------------------------------------------------
            Surface pDestSurf = g_pTempVel.GetSurfaceLevel(0);

            device.GetRenderTargetData(pSurf, pDestSurf);
            Surface pDestSurf2 = g_pTempPos.GetSurfaceLevel(0);

            device.GetRenderTargetData(pSurf2, pDestSurf2);

            float *pDataVel = (float *)pDestSurf.LockRectangle(LockFlags.None).InternalData.ToPointer();
            float *pDataPos = (float *)pDestSurf2.LockRectangle(LockFlags.None).InternalData.ToPointer();

            for (int i = 0; i < MAX_DS; i++)
            {
                for (int j = 0; j < MAX_DS; j++)
                {
                    vel_x[i, j] = *pDataVel++;
                    vel_z[i, j] = *pDataVel++;
                    pDataVel++;     // no usado
                    pDataVel++;     // no usado

                    pos_x[i, j] = *pDataPos++;
                    pos_z[i, j] = *pDataPos++;
                    pos_y[i, j] = *pDataPos++;
                    pDataPos++;     // no usado
                }
            }
            pDestSurf.UnlockRectangle();
            pDestSurf2.UnlockRectangle();

            pSurf.Dispose();
            pSurf2.Dispose();

            device.SetRenderTarget(0, pOldRT);
            device.SetRenderTarget(1, null);
            device.DepthStencilSurface = pOldDS;

            // swap de texturas
            Texture aux = g_pVelocidad;

            g_pVelocidad    = g_pVelocidadOut;
            g_pVelocidadOut = aux;
            aux             = g_pPos;
            g_pPos          = g_pPosOut;
            g_pPosOut       = aux;

            // dibujo pp dicho ----------------------------------------------
            device.Transform.Projection = ant_Proj;
            device.Transform.World      = ant_World;
            device.Transform.View       = ant_View;

            device.BeginScene();
            device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);

            //Renderizar terreno
            if ((bool)Modifiers["dibujar_terreno"])
            {
                terrain.Render();
            }

            // dibujo las particulas como point sprites
            mesh.Effect    = effect;
            mesh.Technique = "DefaultTechnique";
            effect.SetValue("texDiffuseMap", g_pBaseTexture);

            CustomVertex.PositionColored[,] vertices = new CustomVertex.PositionColored[MAX_DS, MAX_DS];
            for (int i = 0; i < MAX_DS; i++)
            {
                for (int j = 0; j < MAX_DS; j++)
                {
                    float x0 = pos_x[i, j];
                    float z0 = pos_z[i, j];
                    float H  = pos_y[i, j];
                    vertices[i, j] = new CustomVertex.PositionColored(x0, H + esfera_radio, z0, Color.Blue.ToArgb());
                }
            }
            g_pVB.SetData(vertices, 0, LockFlags.None);

            device.VertexFormat = CustomVertex.PositionColored.Format;
            device.SetStreamSource(0, g_pVB, 0);
            device.SetTexture(0, null);
            device.SetRenderState(RenderStates.PointSize, 32);
            device.SetRenderState(RenderStates.PointScaleEnable, true);
            device.SetRenderState(RenderStates.PointSpriteEnable, true);
            device.DrawPrimitives(PrimitiveType.PointList, 0, MAX_DS * MAX_DS);
            device.EndScene();
        }
Exemple #24
0
        /// <summary>
        ///     Actualiza los valores de la camara
        /// </summary>
        public void updateCamera(float elapsedTime)
        {
            if (!Enable)
            {
                return;
            }

            //Obtener variacion XY del mouse
            var mouseX = 0f;
            var mouseY = 0f;

            if (Input.keyDown(Key.LeftAlt) && Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_MIDDLE))
            {
                mouseX = Input.XposRelative;
                mouseY = Input.YposRelative;

                diffX += mouseX * elapsedTime * RotationSpeed;
                diffY += mouseY * elapsedTime * RotationSpeed;
            }
            else
            {
                diffX += mouseX;
                diffY += mouseY;
            }

            //Calcular rotacion a aplicar
            var rotX = -diffY / FastMath.PI + BaseRotX;
            var rotY = diffX / FastMath.PI + BaseRotY;

            //Truncar valores de rotacion fuera de rango
            if (rotX > FastMath.PI * 2 || rotX < -FastMath.PI * 2)
            {
                diffY = 0;
                rotX  = 0;
            }

            //Invertir Y de UpVector segun el angulo de rotacion
            if (rotX < -FastMath.PI / 2 && rotX > -FastMath.PI * 3 / 2)
            {
                upVector.Y = -1;
            }
            else if (rotX > FastMath.PI / 2 && rotX < FastMath.PI * 3 / 2)
            {
                upVector.Y = -1;
            }
            else
            {
                upVector.Y = 1;
            }

            //Determinar distancia de la camara o zoom segun el Mouse Wheel
            if (Input.WheelPos != 0)
            {
                diffZ += ZoomFactor * Input.WheelPos * -1;
            }
            var distance = -CameraDistance * diffZ;

            //Limitar el zoom a 0
            if (distance > 0)
            {
                distance = 0;
            }

            //Realizar Transformacion: primero alejarse en Z, despues rotar en X e Y y despues ir al centro de la cmara
            var m = TGCMatrix.Translation(0, 0, -distance)
                    * TGCMatrix.RotationX(rotX)
                    * TGCMatrix.RotationY(rotY)
                    * TGCMatrix.Translation(CameraCenter);

            //Extraer la posicion final de la matriz de transformacion
            nextPos.X = m.M41;
            nextPos.Y = m.M42;
            nextPos.Z = m.M43;

            //Hacer efecto de Pan View
            if (!Input.keyDown(Key.LeftAlt) && Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_MIDDLE))
            {
                var dx           = -Input.XposRelative;
                var dy           = Input.YposRelative;
                var panSpeedZoom = PanSpeed * FastMath.Abs(distance);

                var d = CameraCenter - nextPos;
                d.Normalize();

                var n = TGCVector3.Cross(d, upVector);
                n.Normalize();

                var up   = TGCVector3.Cross(n, d);
                var desf = TGCVector3.Scale(up, dy * panSpeedZoom) - TGCVector3.Scale(n, dx * panSpeedZoom);
                nextPos      = nextPos + desf;
                CameraCenter = CameraCenter + desf;
            }

            //Obtener ViewTGCMatrix haciendo un LookAt desde la posicion final anterior al centro de la camara
            viewTGCMatrix = TGCMatrix.LookAtLH(nextPos, CameraCenter, upVector);
        }
        /// <summary>
        /// Actualiza los valores de la camara
        /// </summary>
        public void updateCamera()
        {
            if (!enable)
            {
                return;
            }

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

            //Obtener variacion XY del mouse
            float mouseX = 0f;
            float mouseY = 0f;

            if (d3dInput.keyDown(Microsoft.DirectX.DirectInput.Key.LeftAlt) && d3dInput.buttonDown(TgcD3dInput.MouseButtons.BUTTON_MIDDLE))
            {
                mouseX = d3dInput.XposRelative;
                mouseY = d3dInput.YposRelative;

                diffX += mouseX * elapsedTime * rotationSpeed;
                diffY += mouseY * elapsedTime * rotationSpeed;
            }
            else
            {
                diffX += mouseX;
                diffY += mouseY;
            }



            //Calcular rotacion a aplicar
            float rotX = (-diffY / FastMath.PI) + baseRotX;
            float rotY = (diffX / FastMath.PI) + baseRotY;

            //Truncar valores de rotacion fuera de rango
            if (rotX > FastMath.PI * 2 || rotX < -FastMath.PI * 2)
            {
                diffY = 0;
                rotX  = 0;
            }

            //Invertir Y de UpVector segun el angulo de rotacion
            if (rotX < -FastMath.PI / 2 && rotX > -FastMath.PI * 3 / 2)
            {
                upVector.Y = -1;
            }
            else if (rotX > FastMath.PI / 2 && rotX < FastMath.PI * 3 / 2)
            {
                upVector.Y = -1;
            }
            else
            {
                upVector.Y = 1;
            }


            //Determinar distancia de la camara o zoom segun el Mouse Wheel
            if (d3dInput.WheelPos != 0)
            {
                diffZ += zoomFactor * d3dInput.WheelPos * -1;
            }
            float distance = -cameraDistance * diffZ;

            //Limitar el zoom a 0
            if (distance > 0)
            {
                distance = 0;
            }


            //Realizar Transformacion: primero alejarse en Z, despues rotar en X e Y y despues ir al centro de la cmara
            Matrix m = Matrix.Translation(0, 0, -distance)
                       * Matrix.RotationX(rotX)
                       * Matrix.RotationY(rotY)
                       * Matrix.Translation(cameraCenter);


            //Extraer la posicion final de la matriz de transformacion
            nextPos.X = m.M41;
            nextPos.Y = m.M42;
            nextPos.Z = m.M43;


            //Hacer efecto de Pan View
            if (!d3dInput.keyDown(Microsoft.DirectX.DirectInput.Key.LeftAlt) && d3dInput.buttonDown(TgcD3dInput.MouseButtons.BUTTON_MIDDLE))
            {
                float dx           = -d3dInput.XposRelative;
                float dy           = d3dInput.YposRelative;
                float panSpeedZoom = panSpeed * FastMath.Abs(distance);

                Vector3 d = cameraCenter - nextPos;
                d.Normalize();

                Vector3 n = Vector3.Cross(d, upVector);
                n.Normalize();

                Vector3 up   = Vector3.Cross(n, d);
                Vector3 desf = Vector3.Scale(up, dy * panSpeedZoom) - Vector3.Scale(n, dx * panSpeedZoom);
                nextPos      = nextPos + desf;
                cameraCenter = cameraCenter + desf;
            }

            //Obtener ViewMatrix haciendo un LookAt desde la posicion final anterior al centro de la camara
            viewMatrix = Matrix.LookAtLH(nextPos, cameraCenter, upVector);
        }
Exemple #26
0
        public void Update(float ElapsedTime, TgcD3dInput Input)
        {
            // Actualizo la posicion del Hacha
            Posicion = env.Camara.Position;
            hachaPersonaje.Position = new Vector3(Posicion.X - 1, Posicion.Y - 0.8f, Posicion.Z);

            // Actualizo la Posicion de la Esfera de Colisión
            BoundingSphere.setCenter(Posicion);

            // Actualizo las Variables de Estado del Personaje
            actualizarEstado(ElapsedTime);

            actualizarControles(ElapsedTime);

            if (this.Muerto)
            {
                env.musica.selectionSound("Sonido\\game_over.mp3");
                env.musica.startSound();
            }
            else
            {
                // Creo la fogata
                if (env.terreno.activarFogata && !env.terreno.ubicacionFogataFija)
                {
                    env.terreno.fogata.Position     = new Vector3(env.Camara.Position.X - (1 * env.terreno.SceneScaleXZ), env.terreno.CalcularAlturaTerreno((env.Camara.Position.X - (1 * env.terreno.SceneScaleXZ)) / env.terreno.SceneScaleXZ, env.Camara.Position.Z / env.terreno.SceneScaleXZ) * env.terreno.SceneScaleY, env.Camara.Position.Z);
                    env.terreno.ubicacionFogataFija = true;
                }

                // Verifico cuantos objetos estan Cerca
                env.objetosCerca = 0;
                foreach (var objeto in env.terreno.SceneMeshes)
                {
                    if (estaCerca(objeto))
                    {
                        env.objetosCerca++;

                        // Si el objeto es una Fruta
                        if (objeto.Name.StartsWith("Fruta") && env.Input.keyPressed(Key.E))
                        {
                            Inventario[0].cantidad++;

                            // Desactivo el objeto y lo muevo a un lugar lejano ya que no puedo sacarlos de SceneMeshes
                            objeto.Enabled = false;
                            objeto.dispose();
                            objeto.Position = new Vector3(0, 0, 0);
                        }

                        // Si el objeto es una Palmera
                        if (objeto.Name.StartsWith("Palmera") && Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                        {
                            sonidoHacha(true);
                            env.sonidoHacha = true;

                            Inventario[2].cantidad++;

                            // Desactivo el objeto y lo muevo a un lugar lejano ya que no puedo sacarlos de SceneMeshes
                            objeto.Enabled = false;
                            objeto.dispose();
                            objeto.Position = new Vector3(0, 0, 0);
                        }

                        // Si el objeto es un Pino
                        if (objeto.Name.StartsWith("Pino") && Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                        {
                            sonidoHacha(true);
                            env.sonidoHacha = true;

                            Inventario[2].cantidad++;

                            // Desactivo el objeto y lo muevo a un lugar lejano ya que no puedo sacarlos de SceneMeshes
                            objeto.Enabled = false;
                            objeto.dispose();
                            objeto.Position = new Vector3(0, 0, 0);
                        }

                        // Si el objeto es una Piedra
                        if (objeto.Name.StartsWith("Roca") && Input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                        {
                            sonidoHacha(true);
                            env.sonidoHacha = true;

                            Inventario[3].cantidad++;

                            // Desactivo el objeto y lo muevo a un lugar lejano ya que no puedo sacarlos de SceneMeshes
                            objeto.Enabled = false;
                            objeto.dispose();
                            objeto.Position = new Vector3(0, 0, 0);
                        }
                    }
                }
            }
        }
Exemple #27
0
        /// <summary>
        /// Construir caja
        /// </summary>
        public override void doCreation()
        {
            TgcD3dInput input = GuiController.Instance.D3dInput;

            switch (currentCreatingState)
            {
            case CreatingBoxState.DraggingSize:

                //Si hacen clic con el mouse, ver si hay colision con el suelo
                if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    //Determinar el size en XZ del box
                    Vector3 collisionPoint = Control.Grid.getPicking();

                    //Obtener extremos del rectángulo de selección
                    Vector3 min = Vector3.Minimize(initSelectionPoint, collisionPoint);
                    Vector3 max = Vector3.Maximize(initSelectionPoint, collisionPoint);
                    min.Y = initSelectionPoint.Y;
                    max.Y = initSelectionPoint.Y + 0.2f;

                    //Configurar BOX
                    mesh.setExtremes(min, max);
                    mesh.updateValues();
                }
                //Solto el clic del mouse, pasar a configurar el Height del box
                else if (input.buttonUp(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    //Tiene el tamaño minimo tolerado
                    Vector3 size = mesh.BoundingBox.calculateSize();
                    if (size.X > 1 && size.Z > 1)
                    {
                        currentCreatingState  = CreatingBoxState.DraggingHeight;
                        creatingBoxInitMouseY = input.Ypos;
                    }
                    //Sino, descartar
                    else
                    {
                        Control.CurrentState = MeshCreatorControl.State.CreatePrimitiveSelected;
                        mesh.dispose();
                        mesh = null;
                    }
                }

                break;

            case CreatingBoxState.DraggingHeight:

                //Si presiona clic, terminar de configurar la altura y generar box definitivo
                if (input.buttonPressed(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    //Guardar size original del Box para hacer Scaling
                    originalSize = mesh.BoundingBox.calculateSize();

                    //Dejar cargado para que se pueda crear un nuevo box
                    Control.CurrentState      = MeshCreatorControl.State.CreatePrimitiveSelected;
                    Control.CreatingPrimitive = new BoxPrimitive(Control);

                    //Agregar box a la lista de modelos
                    Control.addMesh(this);

                    //Seleccionar Box
                    Control.SelectionRectangle.clearSelection();
                    Control.SelectionRectangle.selectObject(this);
                    Control.updateModifyPanel();
                }
                //Determinar altura en base a la posicion Y del mouse
                else
                {
                    float heightY         = creatingBoxInitMouseY - input.Ypos;
                    float adjustedHeightY = MeshCreatorUtils.getMouseIncrementHeightSpeed(Control.Camera, this.BoundingBox, heightY);

                    Vector3 min = mesh.BoundingBox.PMin;
                    min.Y = initSelectionPoint.Y;
                    Vector3 max = mesh.BoundingBox.PMax;
                    max.Y = initSelectionPoint.Y + adjustedHeightY;

                    //Configurar BOX
                    mesh.setExtremes(min, max);
                    mesh.updateValues();
                }

                break;
            }
        }
        /// <summary>
        /// Actualizar y dibujar seleccion
        /// </summary>
        public void render()
        {
            TgcD3dInput input = GuiController.Instance.D3dInput;

            //Mantiene el mouse apretado
            if (input.buttonDown(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                //Definir recuadro
                Vector2 mousePos = new Vector2(input.Xpos, input.Ypos);
                Vector2 min      = Vector2.Minimize(initMousePos, mousePos);
                Vector2 max      = Vector2.Maximize(initMousePos, mousePos);

                rectMesh.updateMesh(min, max);
            }
            //Solo el mouse
            else if (input.buttonUp(TgcD3dInput.MouseButtons.BUTTON_LEFT))
            {
                //Definir recuadro
                Vector2   mousePos = new Vector2(input.Xpos, input.Ypos);
                Vector2   min      = Vector2.Minimize(initMousePos, mousePos);
                Vector2   max      = Vector2.Maximize(initMousePos, mousePos);
                Rectangle r        = new Rectangle((int)min.X, (int)min.Y, (int)(max.X - min.X), (int)(max.Y - min.Y));

                //Usar recuadro de seleccion solo si tiene un tamaño minimo
                if (r.Width > 1 && r.Height > 1)
                {
                    //Limpiar seleccionar anterior si no estamos agregando en forma aditiva
                    if (!selectiveObjectsAdditive)
                    {
                        clearSelection();
                    }

                    //Buscar que objetos del escenario caen dentro de la seleccion y elegirlos
                    foreach (EditorPrimitive p in control.Meshes)
                    {
                        //Solo los visibles
                        if (p.Visible)
                        {
                            //Ver si hay colision contra la proyeccion del AABB del mesh
                            //Rectangle primRect = MeshCreatorUtils.projectAABB(p.BoundingBox);
                            Rectangle primRect;
                            if (MeshCreatorUtils.projectBoundingBox(p.BoundingBox, out primRect))
                            {
                                if (r.IntersectsWith(primRect))
                                {
                                    //Agregar el objeto en forma aditiva
                                    if (selectiveObjectsAdditive)
                                    {
                                        selectOrRemoveObjectIfPresent(p);
                                    }
                                    //Agregar el objeto en forma simple
                                    else
                                    {
                                        selectObject(p);
                                    }
                                }
                            }
                        }
                    }
                }
                //Si el recuadro no tiene tamaño suficiente, hacer seleccion directa
                else
                {
                    doDirectSelection(selectiveObjectsAdditive);
                }

                control.CurrentState = MeshCreatorControl.State.SelectObject;

                //Si quedo algo seleccionado activar gizmo
                if (control.SelectionList.Count > 0)
                {
                    activateCurrentGizmo();
                }

                //Actualizar panel de Modify con lo que se haya seleccionado, o lo que no
                control.updateModifyPanel();
            }



            //Dibujar recuadro
            rectMesh.render();
        }