public void ApplyForce(SimObject simObject)
        {
            //get the direction vector
            direction = simObjectA.CurrPosition - simObjectB.CurrPosition;

            //check for zero vector
            if (direction != Vector3.Zero)
            {
                //get length
                currLength = direction.Length();

                //normalize
                direction.Normalize();

                //add spring force
                force = -stiffness * ((currLength - restLength) * direction);

                //add spring damping force
                force += -damping * Vector3.Dot(simObjectA.CurrVelocity - simObjectB.CurrVelocity, direction) * direction;

                //apply the equal and opposite forces to the objects
                simObjectA.ResultantForce += force;
                simObjectB.ResultantForce += -force;
            }
        }
示例#2
0
        public void Move(Vector3 dir, float amount)
        {
            if (dir.Length() != 1 && dir.Length() != 0)
                dir.Normalize();

            Position += Vector3.Transform(dir * amount, Matrix.CreateRotationX(Pitch) * Matrix.CreateRotationY(Yaw));
        }
示例#3
0
        void RenderResults(RenderMode renderMode, simengine.MatrixTransforms transforms, simengine.CameraEntity currentCamera)
        {
            _timeAttenuationHandle.SetValue(new xna.Vector4(100 * (float)Math.Cos(_appTime * (1.0f / SCAN_INTERVAL)), 0, 0, 1));

            // render impact points as a quad
            xna.Matrix inverseViewRotation = currentCamera.ViewMatrix;
            inverseViewRotation.M41 = inverseViewRotation.M42 = inverseViewRotation.M43 = 0;
            xna.Matrix.Invert(ref inverseViewRotation, out inverseViewRotation);
            xna.Matrix localTransform = xna.Matrix.CreateFromAxisAngle(new xna.Vector3(1, 0, 0), (float)-Math.PI / 2) * inverseViewRotation;

            simengine.SimulationEngine.GlobalInstance.Device.DepthStencilState = xnagrfx.DepthStencilState.DepthRead;
            for (int i = 0; i < _lastResults.ImpactPoints.Count; i++)
            {
                xna.Vector3 pos = new xna.Vector3(_lastResults.ImpactPoints[i].Position.X,
                                                  _lastResults.ImpactPoints[i].Position.Y,
                                                  _lastResults.ImpactPoints[i].Position.Z);

                xna.Vector3 resultDir = pos - Position;
                resultDir.Normalize();

                localTransform.Translation = pos - .02f * resultDir;
                transforms.World           = localTransform;

                base.Render(renderMode, transforms, Meshes[0]);
            }
            simengine.SimulationEngine.GlobalInstance.Device.DepthStencilState = xnagrfx.DepthStencilState.Default;
        }
示例#4
0
        private void KeyboardControl()
        {
            if (Input.Y == 1)
            {
                Velocity += ACCELERATION * Direction;
            }
            else if (Input.Y == -1)
            {
                Velocity -= ACCELERATION * Direction;
            }

            if (Input.X == 1)
            {
                Velocity += ACCELERATION * Right;
            }
            else if (Input.X == -1)
            {
                Velocity -= ACCELERATION * Right;
            }

            else if (InputManager.IsKeyDown(Keys.Space))
            {
                Velocity += Up * ACCELERATION;
            }
            else if (InputManager.IsKeyDown(Keys.LeftShift))
            {
                Velocity -= Up * ACCELERATION;
            }



            if (Input.Y == 0)
            {
                var dir = Direction;
                dir.Y = 0;
                var dot = Vector3.Dot(Velocity, Vector3.Normalize(Direction));
                Velocity -= Math.Sign(dot) * Direction * DECELERATION;
            }

            if (Input.X == 0)
            {
                var dir = Direction;
                dir.Y = 0;
                var vel = Velocity;
                vel.Y = 0;
                var dot = Vector3.Dot(Velocity, Vector3.Normalize(Right));
                Velocity -= Math.Sign(dot) * Right * DECELERATION;
            }

            if (Velocity.Length() < 1f && Input.X == 0 && Input.Y == 0)
            {
                Velocity = new Vector3(0);
            }

            // MaxSpeed
            if (Velocity.Length() > MAX_SPEED)
            {
                Velocity = Vector3.Normalize(Velocity) * MAX_SPEED;
            }
        }
示例#5
0
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            _graphics.GraphicsDevice.Clear(Color.Black);
            //tree.Draw();
            _graphics.GraphicsDevice.VertexDeclaration = _vertexDeclaration;

            // Update our camera
            UpdateCameraThirdPerson();

            _basicEffect.Begin();
            _basicEffect.Projection = _proj;
            _basicEffect.View       = _view;

            _basicEffect.Alpha         = 1.0f;
            _basicEffect.DiffuseColor  = new Vector3(.95f, .95f, .95f);
            _basicEffect.SpecularColor = new Vector3(0.05f, 0.05f, 0.05f);
            _basicEffect.SpecularPower = 5.0f;

            _basicEffect.AmbientLightColor               = new Vector3(0.75f, 0.75f, 0.75f);
            _basicEffect.DirectionalLight0.Enabled       = true;
            _basicEffect.DirectionalLight0.DiffuseColor  = Vector3.One;
            _basicEffect.DirectionalLight0.Direction     = Vector3.Normalize(new Vector3(1.0f, -1.0f, 0.0f));
            _basicEffect.DirectionalLight0.SpecularColor = Vector3.One;

            _basicEffect.DirectionalLight1.Enabled      = true;
            _basicEffect.DirectionalLight1.DiffuseColor = new Vector3(0.1f, 0.1f, 0.1f);
            _basicEffect.DirectionalLight1.Direction    = Vector3.Normalize(new Vector3(-1.0f, -1.0f, 1.0f));

            _basicEffect.LightingEnabled = true;

            foreach (var pass in _basicEffect.CurrentTechnique.Passes)
            {
                pass.Begin();
                _graphics.GraphicsDevice.RenderState.CullMode         = CullMode.None;
                _graphics.GraphicsDevice.RenderState.FillMode         = FillMode.WireFrame;
                _graphics.GraphicsDevice.RenderState.AlphaBlendEnable = true;

                // Make the renderers draw their stuff
                base.Draw(gameTime);

                _graphics.GraphicsDevice.RenderState.FillMode         = FillMode.Solid;
                _graphics.GraphicsDevice.RenderState.CullMode         = CullMode.CullClockwiseFace;
                _graphics.GraphicsDevice.RenderState.AlphaBlendEnable = false;
                pass.End();
            }


            _basicEffect.End();

            DrawCameraState();
            //_spriteBatch.Begin();
            //_spriteBatch.DrawString(_spriteFont, "Esc: Opens the console.",
            //                        new Vector2(10, _graphics.GraphicsDevice.Viewport.Height - 30), Color.White);
            //_spriteBatch.End();

            GraphicsDevice.RenderState.DepthBufferEnable = true;
            GraphicsDevice.RenderState.AlphaBlendEnable  = false;
        }
示例#6
0
 public void Normalize()
 {
     Vector3 v1 = new Vector3(-10.5f, 0.2f, 1000.0f);
     Vector3 v2 = new Vector3(-10.5f, 0.2f, 1000.0f);
     v1.Normalize();
     var expectedResult = new Vector3(-0.0104994215f, 0.000199988979f, 0.999944866f);
     Assert.That(expectedResult, Is.EqualTo(v1).Using(Vector3Comparer.Epsilon));
     v2 = Vector3.Normalize(v2);
     Assert.That(expectedResult, Is.EqualTo(v2).Using(Vector3Comparer.Epsilon));
 }
示例#7
0
        public Camera(Vector3 Position, Vector3 Target, Vector3 Up)
        {
            this.Position  = Position;
            this.Target    = Target;
            this.Direction = Vector3.Normalize(this.Position - this.Target);

            this.Right = Vector3.Normalize(Vector3.Cross(Up, Direction));
            this.Up    = Vector3.Normalize(Vector3.Cross(this.Direction, this.Right));

            this.View = Matrix.CreateLookAt(Position, Target, Up);
            GroundRay = new Raycast(Position, Position + Vector3.Down * HEIGHT);
        }
示例#8
0
        private float DistanceToPatch(Vector3 min, Vector3 max, float radius)
        {
            Vector3 mid1 = (min + max) / 2;

            if (mid1 == Vector3.Zero)
            {
                mid1.Z = min.Z;
            }

            Vector3 surfaceMidPoint = Vector3.Transform(Vector3.Normalize(mid1) * radius, Transform.AbsoluteTransform);

            return(surfaceMidPoint.Length());
        }
示例#9
0
        public override void Initialise()
        {
            CameraDirection = Vector3.Zero - World.Translation;
            CameraDirection.Normalize();
            CameraUpDirection = Vector3.Up;
            CameraTarget = World.Translation + CameraDirection;

            CreateLookAt(StartTarget);

            projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, AspectRatio, NearPlane, FarPlane);

            base.Initialise();
        }
示例#10
0
        public void Update(GameTime gameTime)
        {
            // If window is focused
            if (Game1.Instance.IsActive)
            {
                GetInput();
                MouseControl();
            }
            else
            {
                First = true;
            }

            if (InputManager.IsKeyDown(Keys.F1))
            {
                IsFlying = true;
            }
            if (InputManager.IsKeyDown(Keys.F2))
            {
                IsFlying = false;
            }

            KeyboardControl();

            if (!IsFlying)
            {
                GroundRay.Start = Position;
                GroundRay.End   = Position - new Vector3(0, HEIGHT, 0);
                CollisionResult?result = CollisionHelper.IsCollidingWithWorld(GroundRay);
                IsGrounded = result != null;

                if (IsGrounded)
                {
                    Position   = Vector3.Lerp(Position, new Vector3(Position.X, result.Value.VoxelPosition.Y + HEIGHT, Position.Z), 0.2f);
                    Velocity.Y = 0;
                }

                else
                {
                    Velocity -= GRAVITY * Up * (float)gameTime.ElapsedGameTime.TotalSeconds;
                }
            }

            Direction = Vector3.Lerp(Direction, TargetDirection, Smoothing);

            DestroyRaycast(25f);

            Position  += Velocity * (float)gameTime.ElapsedGameTime.TotalSeconds;
            this.Right = Vector3.Normalize(Vector3.Cross(Up, Direction));
            this.View  = Matrix.CreateLookAt(Position, Position + Direction, Up);
        }
示例#11
0
        private float DistanceToPatch(Vector3 min, Vector3 max, float radius)
        {
            Vector3 mid1 = (min + max) / 2;

            if (mid1 == Vector3.Zero)
            {
                mid1.Z = min.Z;
            }

            Vector3 surfaceMidPoint = Vector3.Transform(Vector3.Normalize(mid1) * radius, Transform.AbsoluteTransform);
            Vector3 toMidPoint      = SystemCore.ActiveCamera.Position - surfaceMidPoint;

            return(toMidPoint.Length());
        }
        void OnLoaded(object sender, RoutedEventArgs e)
        {
            ActorFormControl.RuntimeContent = DataContext as RuntimeContentViewModel;
            ActorFormControl.LoadContent();
            ActorFormControl.ResetActorOrientation(defaultActorOrientation);

            // コントロールに設定されたカメラ座標とモデル姿勢行列を初期値として記憶しておきます。
            defaultCameraPosition = ActorFormControl.CameraPosition;

            // 光源をデフォルトとは違う位置に設定します (デフォルトは方向が Vector3.Down の光源)。
            var direction = new Vector3(1, -1, -1);
            direction.Normalize();
            ActorFormControl.SceneSettings.DirectionalLight0.Direction = direction;
        }
示例#13
0
        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                if (curCamera != null && SimulatorContainer.IsMouseCaptured)
                {
                    var p    = e.GetPosition(SimulatorContainer);
                    var drag = new Vector2((float)p.X - mouseStart.X, (float)p.Y - mouseStart.Y);
                    mouseStart = new Vector2((float)p.X, (float)p.Y);
                    xnaTypes.Vector3 view = curCamera.Camera.LookAt - curCamera.Camera.Location;
                    view.Normalize();
                    switch (dragType)
                    {
                    case DragType.LOOK:
                        xnaTypes.Vector3 up  = new xnaTypes.Vector3(0, 1, 0);
                        float            dot = xnaTypes.Vector3.Dot(view, up);
                        if (Math.Abs(dot) > 0.99)
                        {
                            up += new xnaTypes.Vector3(0.1f, 0, 0);
                            up.Normalize();
                        }
                        xnaTypes.Vector3 right = xnaTypes.Vector3.Cross(view, up);
                        view = xnaTypes.Vector3.Multiply(view, 10f);
                        view = xnaTypes.Vector3.Transform(view, xnaTypes.Matrix.CreateFromAxisAngle(up, (float)(-drag.X * Math.PI / 500)));
                        view = xnaTypes.Vector3.Transform(view, xnaTypes.Matrix.CreateFromAxisAngle(right, (float)(-drag.Y * Math.PI / 500)));

                        curCamera.Camera.LookAt = curCamera.Camera.Location + view;
                        break;

                    case DragType.MOVE:
                        var right2 = xnaTypes.Vector3.Cross(view, new xnaTypes.Vector3(0, 1, 0));
                        var up2    = xnaTypes.Vector3.Cross(right2, view);
                        right2 *= (drag.X * 0.05f);
                        up2    *= (-drag.Y * 0.05f);
                        var delta = right2 + up2;
                        curCamera.Camera.LookAt   += delta;
                        curCamera.Camera.Location += delta;
                        break;
                    }
                }
            }
            catch (Exception err)
            {
                GUIUtilities.ReportUnexpectedException(err);
            }
        }
        public override void Apply(Entity entity, DrawData? drawData)
        {
            if (entity == null)
                _shader.Parameters["uLightSource"].SetValue(Vector3.Zero);
            else
            {
                float num1 = 0.0f;
                if (drawData.HasValue)
                    num1 = drawData.Value.rotation;

                Vector2 vector2_1 = entity.position;
                float x1 = (float)entity.width;
                float y1 = (float)entity.height;
                Vector2 vector2_2 = vector2_1 + new Vector2(x1, y1) * 0.1f;
                float x2 = x1 * 0.8f;
                float y2 = y1 * 0.8f;
                Vector3 subLight1 = Lighting.GetSubLight(vector2_2 + new Vector2(x2 * 0.5f, 0.0f));
                Vector3 subLight2 = Lighting.GetSubLight(vector2_2 + new Vector2(0.0f, y2 * 0.5f));
                Vector3 subLight3 = Lighting.GetSubLight(vector2_2 + new Vector2(x2, y2 * 0.5f));
                Vector3 subLight4 = Lighting.GetSubLight(vector2_2 + new Vector2(x2 * 0.5f, y2));
                float num2 = subLight1.X + subLight1.Y + subLight1.Z;
                float num3 = subLight2.X + subLight2.Y + subLight2.Z;
                float num4 = subLight3.X + subLight3.Y + subLight3.Z;
                float num5 = subLight4.X + subLight4.Y + subLight4.Z;
                Vector2 spinningpoint = new Vector2(num4 - num3, num5 - num2);
                if ((double)spinningpoint.Length() > 1.0)
                {
                    float num6 = 1f;
                    spinningpoint /= num6;
                }

                if (entity.direction == -1)
                    spinningpoint.X *= -1f;

                spinningpoint = Utils.RotatedBy(spinningpoint, -(double)num1, new Vector2());
                Vector3 vector3 = new Vector3(spinningpoint, (float)(1.0 - ((double)spinningpoint.X * (double)spinningpoint.X + (double)spinningpoint.Y * (double)spinningpoint.Y)));
                vector3.X *= 2f;
                vector3.Y -= 0.15f;
                vector3.Y *= 2f;
                vector3.Normalize();
                vector3.Z *= 0.6f;
                _shader.Parameters["uLightSource"].SetValue(vector3);
            }
            base.Apply(entity, drawData);
        }
        // process messages from the UI Form
        void OnWinformMessageHandler(FromWinformMsg msg)
        {
            switch (msg.Command)
            {
            case FromWinformMsg.MsgEnum.Loaded:
                // the windows form is ready to go
                _embeddedSimUI = (EmbeddedSimUI)msg.Object;
                WinFormsServicePort.FormInvoke(delegate() { _embeddedSimUI.SetHeadless(_defaultConfig.Headless); });
                break;

            case FromWinformMsg.MsgEnum.Drag:
                if (_observer != null)
                {
                    Vector2          drag = (Vector2)msg.Object;
                    xnaTypes.Vector3 view = _observer.LookAt - _observer.Location;
                    view.Normalize();
                    xnaTypes.Vector3 up  = new xnaTypes.Vector3(0, 1, 0);
                    float            dot = xnaTypes.Vector3.Dot(view, up);
                    if (Math.Abs(dot) > 0.99)
                    {
                        up += new xnaTypes.Vector3(0.1f, 0, 0);
                        up.Normalize();
                    }
                    xnaTypes.Vector3 right = xnaTypes.Vector3.Cross(view, up);
                    view = xnaTypes.Vector3.Multiply(view, 10f);
                    view = xnaTypes.Vector3.Transform(view, xnaTypes.Matrix.CreateFromAxisAngle(up, (float)(-drag.X * Math.PI / 500)));
                    view = xnaTypes.Vector3.Transform(view, xnaTypes.Matrix.CreateFromAxisAngle(right, (float)(-drag.Y * Math.PI / 500)));

                    _observer.LookAt = _observer.Location + view;
                }
                break;

            case FromWinformMsg.MsgEnum.Zoom:
                if (_observer != null)
                {
                    Vector2          drag = (Vector2)msg.Object;
                    xnaTypes.Vector3 view = _observer.LookAt - _observer.Location;
                    view.Normalize();
                    view                = xnaTypes.Vector3.Multiply(view, drag.X * 0.1f);
                    _observer.LookAt   += view;
                    _observer.Location += view;
                }
                break;
            }
        }
示例#16
0
 private void OnMouseWheel(object sender, MouseWheelEventArgs e)
 {
     try
     {
         if (curCamera != null)
         {
             xnaTypes.Vector3 view = curCamera.Camera.LookAt - curCamera.Camera.Location;
             view.Normalize();
             view = xnaTypes.Vector3.Multiply(view, e.Delta * 0.01f);
             curCamera.Camera.LookAt   += view;
             curCamera.Camera.Location += view;
         }
     }
     catch (Exception err)
     {
         GUIUtilities.ReportUnexpectedException(err);
     }
 }
示例#17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ColoredTerrain" /> class.
        /// </summary>
        /// <param name="heightMap">The height map.</param>
        /// <param name="coloringMethod">The coloring method.</param>
        public ColoredTerrain(GraphicsDevice device, IHeightMap heightMap, IHeightToColorTranslationMethod coloringMethod)
        {
            this.effect = new BasicEffect(device);
            this.effect.VertexColorEnabled = true;
            Vector3 lightDir = new Vector3(1, -1, -1);
            lightDir.Normalize();
            this.effect.LightingEnabled = true;
            this.effect.PreferPerPixelLighting = true;
            this.effect.DirectionalLight0.Direction = lightDir;

            this.Width = heightMap.Width;
            this.Height = heightMap.Height;
            this.heightMap = heightMap;
            this.coloringMethod = coloringMethod;

            this.SetUpVertices();
            this.SetUpIndices();
            this.CalculateNormals();
        }
        public void SatisfyConstraint()
        {
            //calculate direction
            direction = simObj2.CurrPosition - simObj1.CurrPosition;

            //calculate current length
            currentLength = direction.Length();

            //check for zero vector
            if (direction != Vector3.Zero)
            {
                //normalize direction vector
                direction.Normalize();

                //move to goal positions
                moveVector = 0.5f * (currentLength - length) * direction;
                simObj1.CurrPosition += moveVector;
                simObj2.CurrPosition += -moveVector;
            }
        }
            public ObjectRenderer(MathboxRenderer mathboxRenderer)
            {
                Parent             = mathboxRenderer;
                DisplayListManager = Parent.DisplayListManager;
                Memory             = Parent.Memory;

#if WIDESCREEN_STARS
                // load 123 stars from ROM starfield
                byte[] table = Parent.Machine.Mathbox.ROM[2];
                for (int n = 0; n < 123; n++)
                {
                    int   addr = 0x3140 + n * 8;
                    Int16 x    = (Int16)(table[addr & 0x1FFF] * 256 + table[(addr + 1) & 0x1FFF]); addr += 2;
                    Int16 y    = (Int16)(table[addr & 0x1FFF] * 256 + table[(addr + 1) & 0x1FFF]); addr += 2;
                    Int16 z    = (Int16)(table[addr & 0x1FFF] * 256 + table[(addr + 1) & 0x1FFF]); addr += 2;
                    Stars[n] = new Vector3(x, y, z);
                }

                // fill in the blanks with some more random stars
                PRNG r = new PRNG(0xDEAD);
                for (int n = 123; n < Stars.Length;)
                {
                    const int size  = 10000;
                    double    theta = 2 * Math.PI * r.NextDouble;
                    double    phi   = Math.Acos(1 - 2 * r.NextDouble);
                    double    x     = size * Math.Sin(phi) * Math.Cos(theta);
                    double    y     = size * Math.Sin(phi) * Math.Sin(theta);
                    double    z     = size * Math.Abs(Math.Cos(phi));
                    if (x < -3000 || x > 3500)
                    {
                        Vector3 v = new Vector3((float)x, (float)y, (float)z);
                        v.Normalize();
                        v         *= 10000;
                        Stars[n++] = v;
                    }
                }
#endif
            }
示例#20
0
        public void GetHeightAndNormal(Vector3 position, out float height, out Vector3 normal)
        {
            Vector3 positionOnHeightmap = position - ModelMatrix.Translation;

            int left, bottom;

            left = ((int)positionOnHeightmap.X + (int)halfTerrainWidth) / (int)blockScale;
            bottom = ((int)positionOnHeightmap.Z + (int)halfTerrainDepth) / (int)blockScale;

            float xNormalized = ((positionOnHeightmap.X + halfTerrainWidth) % blockScale) / blockScale;
            float zNormalized = ((positionOnHeightmap.Z + halfTerrainDepth) % blockScale) / blockScale;

            float bottomHeight = MathHelper.Lerp(
                verticesArrray[PlaceInArray(bottom, left)].Y,
                verticesArrray[PlaceInArray(bottom, left + 1)].Y,
                xNormalized);

            float topHeight = MathHelper.Lerp(
                verticesArrray[PlaceInArray(bottom + 1, left)].Y,
                verticesArrray[PlaceInArray(bottom + 1, left + 1)].Y,
                xNormalized);

            height = MathHelper.Lerp(bottomHeight, topHeight, zNormalized);

            Vector3 bottomNormal = Vector3.Lerp(
               normalArray[PlaceInArray(bottom, left)],
               normalArray[PlaceInArray(bottom, left + 1)],
                xNormalized);

            Vector3 topNormal = Vector3.Lerp(
               normalArray[PlaceInArray(bottom + 1, left)],
               normalArray[PlaceInArray(bottom + 1, left + 1)],
               xNormalized);

            normal = Vector3.Lerp(bottomNormal, topNormal, zNormalized);
            normal.Normalize();
        }
示例#21
0
        public Rangefinder(IGameEntity entity)
        {
            SensingEntity = entity;

            // Initialize feeler directions.
            Vector3 forwardDir = new Vector3(entity.Heading, 0.0f);
            forwardDir.Normalize();

            Vector3 leftForwardDir = Vector3.Transform(forwardDir,
                Matrix.CreateRotationZ(MathHelper.ToRadians(-AngleBetweenFeelers)));
            leftForwardDir.Normalize();

            Vector3 rightForwardDir = Vector3.Transform(forwardDir,
                Matrix.CreateRotationZ(MathHelper.ToRadians(AngleBetweenFeelers)));
            rightForwardDir.Normalize();

            // Add 3 feelers.
            Vector3 position = new Vector3(entity.Position, 0.0f);
            Feelers.Add(new Ray(position, leftForwardDir));
            Feelers.Add(new Ray(position, forwardDir));
            Feelers.Add(new Ray(position, rightForwardDir));

            rangefinderDebugger = new RangefinderDebugger(this);
        }
示例#22
0
        private void RenderConnections(PlanetNode node)
        {
            List <NeighbourTracker.Connection> connections = neighbourTracker.GetConnections(node);
            Color nodeQuadrantColor = Color.Red;

            if (neighbourTracker.nodeDictionary.ContainsKey(node.GetKeyPoint()))
            {
                NeighbourTrackerNode trackerNode = neighbourTracker.nodeDictionary[node.GetKeyPoint()];

                if (trackerNode.quadrant == NeighbourTrackerNode.Quadrant.ne)
                {
                    nodeQuadrantColor = Color.White;
                }
                if (trackerNode.quadrant == NeighbourTrackerNode.Quadrant.nw)
                {
                    nodeQuadrantColor = Color.Green;
                }
                if (trackerNode.quadrant == NeighbourTrackerNode.Quadrant.se)
                {
                    nodeQuadrantColor = Color.Pink;
                }
                if (trackerNode.quadrant == NeighbourTrackerNode.Quadrant.sw)
                {
                    nodeQuadrantColor = Color.Yellow;
                }

                DebugShapeRenderer.AddBoundingSphere(new BoundingSphere(node.GetSurfaceMidPoint(), 100f / trackerNode.depth), nodeQuadrantColor);
            }


            foreach (NeighbourTracker.Connection conn in connections)
            {
                DebugShapeRenderer.AddLine(node.GetSurfaceMidPoint(),
                                           Vector3.Transform(Vector3.Normalize(conn.node.keyPoint) * radius, Transform.AbsoluteTransform), Color.Blue);
            }
        }
示例#23
0
        /// <summary>
        /// Finds a supporting entity, the contact location, and the contact normal.
        /// </summary>
        /// <param name="location">Contact point between the wheel and the support.</param>
        /// <param name="normal">Contact normal between the wheel and the support.</param>
        /// <param name="suspensionLength">Length of the suspension at the contact.</param>
        /// <param name="supportingCollidable">Collidable supporting the wheel, if any.</param>
        /// <param name="entity">Supporting object.</param>
        /// <param name="material">Material of the wheel.</param>
        /// <returns>Whether or not any support was found.</returns>
        protected internal override bool FindSupport(out Vector3 location, out Vector3 normal, out float suspensionLength, out Collidable supportingCollidable, out Entity entity, out Material material)
        {
            suspensionLength = float.MaxValue;
            location = Toolbox.NoVector;
            supportingCollidable = null;
            entity = null;
            normal = Toolbox.NoVector;
            material = null;

            Collidable testCollidable;
            RayHit rayHit;

            bool hit = false;

            for (int i = 0; i < detector.CollisionInformation.pairs.Count; i++)
            {
                var pair = detector.CollisionInformation.pairs[i];
                testCollidable = (pair.BroadPhaseOverlap.entryA == detector.CollisionInformation ? pair.BroadPhaseOverlap.entryB : pair.BroadPhaseOverlap.entryA) as Collidable;
                if (testCollidable != null)
                {
                    if (CollisionRules.CollisionRuleCalculator(this, testCollidable) == CollisionRule.Normal &&
                        testCollidable.RayCast(new Ray(wheel.suspension.worldAttachmentPoint, wheel.suspension.worldDirection), wheel.suspension.restLength, out rayHit) &&
                        rayHit.T < suspensionLength)
                    {
                        suspensionLength = rayHit.T;
                        EntityCollidable entityCollidable;
                        if ((entityCollidable = testCollidable as EntityCollidable) != null)
                        {
                            entity = entityCollidable.Entity;
                            material = entityCollidable.Entity.Material;
                        }
                        else
                        {
                            entity = null;
                            supportingCollidable = testCollidable;
                            var materialOwner = testCollidable as IMaterialOwner;
                            if (materialOwner != null)
                                material = materialOwner.Material;
                        }
                        location = rayHit.Location;
                        normal = rayHit.Normal;
                        hit = true;
                    }
                }
            }
            if (hit)
            {
                if (suspensionLength > 0)
                    normal.Normalize();
                else
                    Vector3.Negate(ref wheel.suspension.worldDirection, out normal);
                return true;
            }
            return false;
        }
示例#24
0
 private static Matrix BuildLightViewMatrix(Vector3 lightDirection)
 {
     lightDirection.Normalize();
     var lightProjection = Matrix.CreateOrthographic(21, 21, 1.0f, 60.0f);
     var lightView = Matrix.CreateLookAt(-lightDirection * 10.0f, Vector3.Zero, Vector3.Up);
     return lightView * lightProjection;
 }
示例#25
0
 protected override void Execute(List <CommandEntity> entities)
 {
     foreach (var e in entities)
     {
         var playerEntities = m_contexts.game.GetEntitiesWithPlayerId(e.commandOwner.value);
         if (playerEntities.Count == 0)
         {
             continue;
         }
         var playerEntity = playerEntities.SingleEntity();
         if (e.moveCommand.value.LengthSquared() > 0.1f)
         {
             float   angularSpeed = playerEntity.angularSpeed.value;
             Vector3 dir          = playerEntity.direction.value;
             Vector3 targetDir    = e.moveCommand.value;
             // dot(dir, rot90CCW(targetDir))
             float angle = 0f;
             float dot   = dir.X * -targetDir.Y + dir.Y * targetDir.X;
             // parallel/antiparallel
             if (Math.Abs(dot) <= ANGLE_TOLERANCE)
             {
                 Services.Get <ILogService>().LogInfo("parallel/antiparallel");
                 if (Vector3.Dot(dir, targetDir) < 0f)
                 {
                     angle = angularSpeed * m_timeService.FrameInterval;
                 }
             }
             // targetDir is in right of dir,
             else if (dot > float.Epsilon)
             {
                 Services.Get <ILogService>().LogInfo("targetDir is in right of dir " + dot.ToString());
                 angle = -angularSpeed * m_timeService.FrameInterval;
                 float d = MathHelper.ToDegrees((float)Math.Acos(dot)) - 90f;
                 // over rotation
                 if (Math.Abs(angle) > Math.Abs(d))
                 {
                     angle = d;
                 }
             }
             // targetDir is in left of dir
             else
             {
                 Services.Get <ILogService>().LogInfo("targetDir is in left of dir" + dot.ToString());
                 angle = angularSpeed * m_timeService.FrameInterval;
                 float d = MathHelper.ToDegrees((float)Math.Acos(dot)) - 90f;
                 // over rotate
                 if (Math.Abs(angle) > Math.Abs(d))
                 {
                     angle = d;
                 }
             }
             var quat       = Quaternion.CreateFromAxisAngle(Vector3.Backward, MathHelper.ToRadians(angle));
             var targetQuat = Quaternion.Multiply(playerEntity.rotation.value, quat);
             playerEntity.ReplaceRotation(targetQuat);
             playerEntity.ReplaceDirection(Vector3.Normalize(Vector3.Transform(Vector3.Right, targetQuat)));
             playerEntity.ReplaceSpeed(playerEntity.speed.maxValue, playerEntity.speed.maxValue);
         }
         else
         {
             playerEntity.ReplaceSpeed(0f, playerEntity.speed.maxValue);
         }
     }
 }
示例#26
0
        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                if (curCamera != null && SimulatorContainer.IsMouseCaptured)
                {
                    var p = e.GetPosition(SimulatorContainer);
                    var drag = new Vector2((float)p.X - mouseStart.X, (float)p.Y - mouseStart.Y);
                    mouseStart = new Vector2((float)p.X, (float)p.Y);
                    xnaTypes.Vector3 view = curCamera.Camera.LookAt - curCamera.Camera.Location;
                    view.Normalize();
                    switch (dragType)
                    {
                        case DragType.LOOK:
                            xnaTypes.Vector3 up = new xnaTypes.Vector3(0, 1, 0);
                            float dot = xnaTypes.Vector3.Dot(view, up);
                            if (Math.Abs(dot) > 0.99)
                            {
                                up += new xnaTypes.Vector3(0.1f, 0, 0);
                                up.Normalize();
                            }
                            xnaTypes.Vector3 right = xnaTypes.Vector3.Cross(view, up);
                            view = xnaTypes.Vector3.Multiply(view, 10f);
                            view = xnaTypes.Vector3.Transform(view, xnaTypes.Matrix.CreateFromAxisAngle(up, (float)(-drag.X * Math.PI / 500)));
                            view = xnaTypes.Vector3.Transform(view, xnaTypes.Matrix.CreateFromAxisAngle(right, (float)(-drag.Y * Math.PI / 500)));

                            curCamera.Camera.LookAt = curCamera.Camera.Location + view;
                            break;
                        case DragType.MOVE:
                            var right2 = xnaTypes.Vector3.Cross(view, new xnaTypes.Vector3(0, 1, 0));
                            var up2 = xnaTypes.Vector3.Cross(right2, view);
                            right2 *= (drag.X * 0.05f);
                            up2 *= (-drag.Y * 0.05f);
                            var delta = right2 + up2;
                            curCamera.Camera.LookAt += delta;
                            curCamera.Camera.Location += delta;
                            break;
                    }
                }
            }
            catch (Exception err)
            {
                GUIUtilities.ReportUnexpectedException(err);
            }
        }
示例#27
0
 private void RotateLight(float degrees = 1)
 {
     lightDir = Vector3.TransformNormal(lightDir, Matrix.CreateFromYawPitchRoll(MathHelper.ToRadians(degrees * Game1.GameParameters.LightChangeSpeed), 0, 0));
     lightDir.Normalize();
     Effect.Parameters["xLightDirection"].SetValue(lightDir);
 }
示例#28
0
 private Vector3 calculateNormal(float A, float B, float C, float D)
 {
     Vector3 iVector = new Vector3(
         (A - B),
         Y_Normal,
         (C - D));
     iVector.Normalize();
     return iVector;
 }
示例#29
0
 // for supplying both a new forward and and new up
 public void RegenerateOrthonormalBasis(Vector3 newForward, Vector3 newUp)
 {
     _up = newUp;
     newForward.Normalize();
     RegenerateOrthonormalBasis(newForward);
 }
示例#30
0
        /// <summary>
        /// This is the method that is called to move our avatar
        /// </summary>
        /// <code>
        /// // create the class that does translations
        /// GiveHelpTransforms ght = new GiveHelpTransforms();
        /// // have it load our XML into the SourceXML property
        /// ght.LoadXMLFromFile(
        ///      "E:\\Inetpub\\wwwroot\\GiveHelp\\GiveHelpDoc.xml");
        /// </code>
        void UpdateAvatarPosition()
        {
            var keyboardState = Keyboard.GetState();
            var currentState  = GamePad.GetState(PlayerIndex.One);
            var mouseState    = Mouse.GetState();

            //if (Console.IsOpen()) return;

            if (keyboardState.IsKeyDown(Keys.P))
            {
                System.Console.WriteLine("Open!");
            }

            if (keyboardState.IsKeyDown(Keys.A) || (currentState.DPad.Left == ButtonState.Pressed))
            {
                // move left
                //avatarYaw += RotationSpeed;
                var forwardMovement = Matrix.CreateRotationY(avatarYaw);
                var v = new Vector3(1, 0, 0);
                v = Vector3.Transform(v, forwardMovement);
                avatarPosition.X += v.X;
                avatarPosition.Y += v.Y;
                avatarPosition.Z += v.Z;
            }

            if (keyboardState.IsKeyDown(Keys.D) || (currentState.DPad.Right == ButtonState.Pressed))
            {
                // move right
                //avatarYaw -= RotationSpeed;

                var forwardMovement = Matrix.CreateRotationY(avatarYaw);
                var v = new Vector3(1, 0, 0);
                avatarPosition -= Vector3.Transform(v, forwardMovement);
            }

            if (keyboardState.IsKeyDown(Keys.W) || (currentState.DPad.Up == ButtonState.Pressed))
            {
                //var forwardMovement = Matrix.CreateRotationY(avatarYaw);
                //var v = new Vector3(0, 0, ForwardSpeed);
                //v = Vector3.Transform(v, forwardMovement);
                //avatarPosition.Z += v.Z;
                //avatarPosition.X += v.X;
                var horizontal = avatarPitch.Cos();
                var vertical   = -avatarPitch.Sin();
                var v          = new Vector3(avatarYaw.Sin() * horizontal, vertical, avatarYaw.Cos() * horizontal);
                v.Normalize();
                avatarPosition += v * ForwardSpeed;
            }

            if (keyboardState.IsKeyDown(Keys.S) || (currentState.DPad.Down == ButtonState.Pressed))
            {
                var horizontal = avatarPitch.Cos();
                var vertical   = -avatarPitch.Sin();
                var v          = new Vector3(avatarYaw.Sin() * horizontal, vertical, avatarYaw.Cos() * horizontal);
                v.Normalize();
                avatarPosition -= v * ForwardSpeed;
            }

            if (keyboardState.IsKeyDown(Keys.F))
            {
                avatarPosition.Y = avatarPosition.Y - 1;
            }

            if (keyboardState.IsKeyDown(Keys.R) || keyboardState.IsKeyDown(Keys.Space))
            {
                avatarPosition.Y = avatarPosition.Y + 1;
            }

            if (keyboardState.IsKeyDown(Keys.T))
            {
                _thirdPersonReference.Y = _thirdPersonReference.Y - 0.25f;
            }
            if (keyboardState.IsKeyDown(Keys.G))
            {
                _thirdPersonReference.Y = _thirdPersonReference.Y + 0.25f;
            }

            // adjust speed
            if (keyboardState.IsKeyDown(Keys.OemPlus))
            {
                ForwardSpeed = Math.Min(ForwardSpeed + 0.1f, 15);
            }
            else if (keyboardState.IsKeyDown(Keys.OemMinus))
            {
                ForwardSpeed = Math.Max(ForwardSpeed - 0.1f, 0.1f);
            }


            if (mouseState.LeftButton == ButtonState.Pressed && !mouseLeftButtonDown)
            {
                // select polygon
                mouseLeftButtonDown = true;

                var width  = _graphics.GraphicsDevice.Viewport.Width;
                var height = _graphics.GraphicsDevice.Viewport.Height;
                var x      = mouseState.X;
                var y      = mouseState.Y;

                if (x < 0 || y < 0 || x > width || y > height)
                {
                    return;
                }

                var add = (keyboardState.IsKeyDown(Keys.LeftShift) || keyboardState.IsKeyDown(Keys.RightShift));

                var startPos = new Vector3(x, y, 0);
                var endPos   = new Vector3(x, y, 1);

                var near = _graphics.GraphicsDevice.Viewport.Unproject(startPos, _proj, _view, Matrix.Identity).ToWCell();
                var far  = _graphics.GraphicsDevice.Viewport.Unproject(endPos, _proj, _view, Matrix.Identity).ToWCell();

                var dir = (far - near).NormalizedCopy();
                var ray = new Ray(near, dir);

                TerrainProgram.TerrainManager.SelectedTriangleManager.UpdateSelectedTriangle(ray, add);
            }

            if (mouseState.LeftButton == ButtonState.Released && mouseLeftButtonDown)
            {
                mouseLeftButtonDown = false;
            }
        }
示例#31
0
        private bool RenderParticle(Camera cam, int vertexIndex, int triangleIndex, ref Particle particle)
        {
            float size = particle.Size / 2;

            if (size <= 0)
            {
                return(false);
            }

            Microsoft.Xna.Framework.Vector3 pos = particle.Position;
            if (!emitter.useWorldSpace)
            {
                pos += (Microsoft.Xna.Framework.Vector3)transform.position;
            }

            if (doViewportCulling)
            {
                BoundingSphere sphere = new BoundingSphere(pos, size);
                if (cam.DoFrustumCulling(ref sphere))
                {
                    return(false);
                }
            }

            vertices[vertexIndex].TextureCoordinate     = new Microsoft.Xna.Framework.Vector2(particle.TextureOffset.x, particle.TextureOffset.y + particle.TextureScale.y);
            vertices[vertexIndex].Color                 = particle.Color;
            vertices[vertexIndex + 1].TextureCoordinate = new Microsoft.Xna.Framework.Vector2(particle.TextureOffset.x, particle.TextureOffset.y);
            vertices[vertexIndex + 1].Color             = particle.Color;
            vertices[vertexIndex + 2].TextureCoordinate = new Microsoft.Xna.Framework.Vector2(particle.TextureOffset.x + particle.TextureScale.x, particle.TextureOffset.y + particle.TextureScale.y);
            vertices[vertexIndex + 2].Color             = particle.Color;
            vertices[vertexIndex + 3].TextureCoordinate = new Microsoft.Xna.Framework.Vector2(particle.TextureOffset.x + particle.TextureScale.x, particle.TextureOffset.y);
            vertices[vertexIndex + 3].Color             = particle.Color;

            //rotated particles
            if (stretchParticles == StretchParticles.Billboard)
            {
                Microsoft.Xna.Framework.Vector3 particlePosition = particle.Position;

                Matrix.CreateBillboard(
                    ref particlePosition,
                    ref camPosition,
                    ref camUpVector,
                    camForwardVector,
                    out m
                    );

                Microsoft.Xna.Framework.Vector3 vertical   = new Microsoft.Xna.Framework.Vector3(0, -size, 0);
                Microsoft.Xna.Framework.Vector3 horizontal = new Microsoft.Xna.Framework.Vector3(size, 0, 0);

                m.Translation = Microsoft.Xna.Framework.Vector3.Zero;
                //Microsoft.Xna.Framework.Vector3.Transform(ref p, ref m, out p);

                Microsoft.Xna.Framework.Vector3.Transform(ref vertical, ref m, out vertical);
                Microsoft.Xna.Framework.Vector3.Transform(ref horizontal, ref m, out horizontal);

                vertices[vertexIndex].Position     = pos - vertical + horizontal;
                vertices[vertexIndex + 1].Position = pos - vertical - horizontal;
                vertices[vertexIndex + 2].Position = pos + vertical + horizontal;
                vertices[vertexIndex + 3].Position = pos + vertical - horizontal;
            }

            if (stretchParticles == StretchParticles.Stretched)
            {
                size *= 2;
                Microsoft.Xna.Framework.Vector3 particlePosition = particle.Position;

                //TODO make this work correctly, and add velocityScale functionality.
                Microsoft.Xna.Framework.Vector3 vertical = -particle.Velocity;
                vertical.Normalize();
                vertical *= size * lengthScale;
                Microsoft.Xna.Framework.Vector3 horizontal = -Microsoft.Xna.Framework.Vector3.Cross(vertical, camForwardVector);
                horizontal.Normalize();
                horizontal *= size;

                vertices[vertexIndex].Position     = pos - vertical + horizontal;
                vertices[vertexIndex + 1].Position = pos - vertical - horizontal;
                vertices[vertexIndex + 2].Position = pos + vertical + horizontal;
                vertices[vertexIndex + 3].Position = pos + vertical - horizontal;
            }


            if (stretchParticles == StretchParticles.HorizontalBillboard)
            {
                vertices[vertexIndex].Position     = pos + new Microsoft.Xna.Framework.Vector3(-size, vertexIndex * 0.0001f, size);
                vertices[vertexIndex + 1].Position = pos + new Microsoft.Xna.Framework.Vector3(-size, vertexIndex * 0.0001f, -size);
                vertices[vertexIndex + 2].Position = pos + new Microsoft.Xna.Framework.Vector3(size, vertexIndex * 0.0001f, size);
                vertices[vertexIndex + 3].Position = pos + new Microsoft.Xna.Framework.Vector3(size, vertexIndex * 0.0001f, -size);
            }


            return(true);
        }
示例#32
0
文件: Water.cs 项目: Noxalus/WaterXNA
        private void SetUpVertices()
        {
            // Terrain
            _terrainVertices = new VertexPositionNormalTexture[_terrainSize.X * _terrainSize.Y];
            for (int x = 0; x < _terrainSize.X; x++)
            {
                for (int y = 0; y < _terrainSize.Y; y++)
                {
                    int i = x + y * _terrainSize.X;
                    _terrainVertices[i].Position = new Vector3(x, _terrainHeights[x, y], y);
                    _terrainVertices[i].TextureCoordinate = new Vector2((x / (float)_terrainSize.X),
                        1 - (y / (float)_terrainSize.Y));

                    // Compute normals
                    _terrainVertices[i].Normal = Vector3.Zero;

                    Vector3 normal;
                    float deltaHeight;
                    if (x > 0)
                    {
                        if (x + 1 < _terrainSize.X)
                        {
                            deltaHeight = _terrainHeights[x - 1, y] - _terrainHeights[x + 1, y];
                        }
                        else
                        {
                            deltaHeight = _terrainHeights[x - 1, y] - _terrainHeights[x, y];
                        }
                    }
                    else
                        deltaHeight = _terrainHeights[x, y] - _terrainHeights[x + 1, y];

                    var normalizedVector = new Vector3(0.0f, 1.0f, deltaHeight);
                    normalizedVector.Normalize();
                    _terrainVertices[i].Normal += normalizedVector;
                    if (y > 0)
                    {
                        if (y + 1 < _terrainSize.Y)
                            deltaHeight = _terrainHeights[x, y - 1] - _terrainHeights[x, y + 1];
                        else
                            deltaHeight = _terrainHeights[x, y - 1] - _terrainHeights[x, y];
                    }
                    else
                    {
                        deltaHeight = _terrainHeights[x, y] - _terrainHeights[x, y + 1];
                    }

                    normalizedVector = new Vector3(deltaHeight, 1.0f, 0.0f);
                    normalizedVector.Normalize();
                    _terrainVertices[i].Normal += normalizedVector;
                    _terrainVertices[i].Normal.Normalize();
                }
            }

            // Water
            _waterVertices = new VertexPositionTexture[4];

            // Bottom left
            _waterVertices[0].Position = new Vector3(0, _waterHeight, 0);
            _waterVertices[0].TextureCoordinate = new Vector2(0, 1);

            // Top left
            _waterVertices[1].Position = new Vector3(0, _waterHeight, _terrainSize.Y);
            _waterVertices[1].TextureCoordinate = new Vector2(0, 0);

            // Top right
            _waterVertices[2].Position = new Vector3(_terrainSize.X, _waterHeight, _terrainSize.Y);
            _waterVertices[2].TextureCoordinate = new Vector2(1, 0);

            // Bottom right
            _waterVertices[3].Position = new Vector3(_terrainSize.X, _waterHeight, 0);
            _waterVertices[3].TextureCoordinate = new Vector2(1, 1);
        }
示例#33
0
        public void Update()
        {
            // first translate, then rotate
            
            var gamepad = GamePad.GetState(PlayerIndex.One);
            var keyboard = Keyboard.GetState();

            float triggerR = gamepad.Triggers.Right;
            float triggerL = gamepad.Triggers.Left;
            float thumbLX = gamepad.ThumbSticks.Left.X;
            float thumbLY = gamepad.ThumbSticks.Left.Y;
            float thumbRX = gamepad.ThumbSticks.Right.X;
            float thumbRY = gamepad.ThumbSticks.Right.Y;

            if (keyboard.IsKeyDown(Keys.Left))
                thumbLX = -1f;
            if (keyboard.IsKeyDown(Keys.Right))
                thumbLX = 1f;
            if (Keyboard.GetState().IsKeyDown(Keys.Up))
                thumbLY = 1f;
            if (Keyboard.GetState().IsKeyDown(Keys.Down))
                thumbLY = -1f;

            if (keyboard.IsKeyDown(Keys.A))
                thumbRX = -1f;
            if (keyboard.IsKeyDown(Keys.D))
                thumbRX = 1f;
            if (keyboard.IsKeyDown(Keys.W))
                thumbRY = 1f;
            if (keyboard.IsKeyDown(Keys.S))
                thumbRY = -1f;

            float maxMoveDelta = 1.0f / 60.0f;
            float maxRotDelta = 0.5f * MathHelper.Pi / 60.0f;

            Vector3 up = new Vector3(0.0f, 1.0f, 0.0f);
            Vector3 right = Vector3.Normalize(Vector3.Cross(GetForward(), up));
            Vector3 forwardXY = Vector3.Cross(up, right);

            eye += new Vector3(0.0f, triggerR * maxMoveDelta, 0.0f);
            eye -= new Vector3(0.0f, triggerL * maxMoveDelta, 0.0f);

            eye += forwardXY * thumbLY * maxMoveDelta;
            eye += right * thumbLX * maxMoveDelta;

            forward = Vector3.TransformNormal(forward, Matrix.CreateFromAxisAngle(right, thumbRY * maxRotDelta));
            forward = Vector3.TransformNormal(forward, Matrix.CreateRotationY(thumbRX * -maxRotDelta));
            forward.Normalize();
        }
示例#34
0
        // ------------------------------------------------------------------------
        // set "side" basis vector to normalized cross product of forward and up
        public void SetUnitSideFromForwardAndUp()
        {
            // derive new unit side basis vector from forward and up
            _side = IsRightHanded ? Vector3.Cross(_forward, _up) : Vector3.Cross(_up, _forward);

            _side.Normalize();
        }
示例#35
0
        private Vector3 calculateNormal(Vector3 origin, Vector3 p2, Vector3 p3)
        {
            Vector3 U = (p2 - origin);
            Vector3 V = (p3 - origin);
            Vector3 N = new Vector3(
                U.Y * V.Z - U.Z * V.Y,
                U.Z * V.X - U.X * V.Z,
                U.X * V.Y - U.Y * V.X);
            N.Normalize();

            return N;
        }
示例#36
0
        public Enemy Get(EnemyType type, int speedLevel, int livesLevel, int value)
        {
            Enemy e = EnemiesPools[type].Get();

            e.Name = GetTexture(type);
            e.Type = type;
            e.Simulator = Simulator;
            e.Speed = GetSpeed(type, speedLevel);
            e.LifePoints = e.StartingLifePoints = GetLives(type, livesLevel); ;
            e.CashValue = value;
            e.PointsValue = livesLevel;
            e.Color = ColorsEnemies[type];
            e.Level = (speedLevel + livesLevel) / 2;
            e.FadeInTime = (type == EnemyType.Swarm) ? 250 : 1000;
            e.ImpulseSpeed = (type == EnemyType.Swarm) ? 1f : 0;
            e.ImpulseTime = (type == EnemyType.Swarm) ? 250 : 0;

            if (type == EnemyType.Swarm)
            {
                Vector3 direction = new Vector3(
                    Main.Random.Next(-100, 100),
                    Main.Random.Next(-100, 100),
                    0
                );

                direction.Normalize();

                e.ImpulseDirection = direction;
            }

            return e;
        }
示例#37
0
文件: Game.cs 项目: tangledcode/maze
        protected void UpdateInput()
        {
            KeyboardState newKeyboardState = Keyboard.GetState();
            MouseState newMouseState = Mouse.GetState();

            Vector3 forward = new Vector3(player.Camera.View.X, 0, player.Camera.View.Z);
            forward.Normalize();
            Vector3 side = Vector3.Cross(forward, player.Camera.Up);

            if (newKeyboardState.IsKeyDown(Keys.W))                                          // move forward
            {
                player.Position += player.Camera.View * player.MovementVelocity;
            }
            else if (newKeyboardState.IsKeyDown(Keys.S))                                    // move backwards
            {
                player.Position -= player.Camera.View * player.MovementVelocity;
            }

            if (newKeyboardState.IsKeyDown(Keys.A))                                         // move left
            {
                player.Position -= side * player.MovementVelocity;
            }
            else if (newKeyboardState.IsKeyDown(Keys.D))                                    // move right
            {
                player.Position += side * player.MovementVelocity;
            }

            if (newMouseState != oldMouseState)
            {
                float mouseXDiff = newMouseState.X - oldMouseState.X;
                float mouseYDiff = newMouseState.Y - oldMouseState.Y;

                player.Camera.View = Vector3.Transform(player.Camera.View, Matrix.CreateRotationY(mouseXDiff * player.LookVelocity / 100.0f));
                player.Camera.View = Vector3.Transform(player.Camera.View, Matrix.CreateRotationX(mouseYDiff * player.LookVelocity / 100.0f));
            }

            oldKeyboardState = newKeyboardState;
            oldMouseState = newMouseState;
        }
示例#38
0
        // for when the new forward is NOT know to have unit length
        public void RegenerateOrthonormalBasis(Vector3 newForward)
        {
            newForward.Normalize();

            RegenerateOrthonormalBasisUF(newForward);
        }
示例#39
0
 private void InitializeEffect()
 {
     lightDir = new Vector3(0, -1, -1);
     lightDir.Normalize();
     Effect.CurrentTechnique = Effect.Techniques["MultiTextured"];
     Effect.Parameters["xTexture0"].SetValue(sand);
     Effect.Parameters["xTexture1"].SetValue(grass);
     Effect.Parameters["xTexture2"].SetValue(rock);
     Effect.Parameters["xTexture3"].SetValue(snow);
     Effect.Parameters["xEnableLighting"].SetValue(true);
     this.SetAmbient(.2f);
     Effect.Parameters["xLightDirection"].SetValue(lightDir);
     Effect.Parameters["xWorld"].SetValue(Matrix.Identity);
     Effect.Parameters["xProjection"].SetValue(Projection);
     Effect.Parameters["xEnableBlending"].SetValue(true);
     //this.InitializeFog(2,18,Color.Red);
 }
示例#40
0
        /// <summary>
        /// This is the method that is called to move our avatar 
        /// </summary>
        /// <code>
        /// // create the class that does translations
        /// GiveHelpTransforms ght = new GiveHelpTransforms();
        /// // have it load our XML into the SourceXML property
        /// ght.LoadXMLFromFile(
        ///      "E:\\Inetpub\\wwwroot\\GiveHelp\\GiveHelpDoc.xml");
        /// </code>
        void UpdateState()
        {
            var keyboardState = Keyboard.GetState();
            var gamePadState = GamePad.GetState(PlayerIndex.One);
            var mouseState = Mouse.GetState();

            //if (Console.IsOpen()) return;

            if (keyboardState.IsKeyDown(Keys.P))
            {
                Console.WriteLine("Open!");
            }

            // movement
            if (!IsMenuVisible
                && (keyboardState.IsKeyDown(Keys.A)
                    || (gamePadState.DPad.Left == ButtonState.Pressed)))
            {
                var forwardSpeed = ForwardSpeed;
                if (keyboardState.IsKeyDown(Keys.LeftShift) || keyboardState.IsKeyDown(Keys.RightShift))
                {
                    forwardSpeed *= 0.5f;
                }

                // move left
                //avatarYaw += RotationSpeed;
                var forwardMovement = Matrix.CreateRotationY(avatarYaw);
                var v = new XVector3(1, 0, 0)*forwardSpeed;
                v = XVector3.Transform(v, forwardMovement);
                avatarPosition += v;
            }

            if (!IsMenuVisible
                && (keyboardState.IsKeyDown(Keys.D)
                    || (gamePadState.DPad.Right == ButtonState.Pressed)))
            {
                var forwardSpeed = ForwardSpeed;
                if (keyboardState.IsKeyDown(Keys.LeftShift) || keyboardState.IsKeyDown(Keys.RightShift))
                {
                    forwardSpeed *= 0.5f;
                }

                // move right
                //avatarYaw -= RotationSpeed;
                var forwardMovement = Matrix.CreateRotationY(avatarYaw);
                var v = new XVector3(-1, 0, 0)*forwardSpeed;
                v = XVector3.Transform(v, forwardMovement);
                avatarPosition += v;
            }

            if (!IsMenuVisible
                && (keyboardState.IsKeyDown(Keys.W)
                    || (gamePadState.DPad.Up == ButtonState.Pressed)))
            {
                var forwardSpeed = ForwardSpeed;
                if (keyboardState.IsKeyDown(Keys.LeftShift) || keyboardState.IsKeyDown(Keys.RightShift))
                {
                    forwardSpeed *= 0.5f;
                }

                //var forwardMovement = Matrix.CreateRotationY(avatarYaw);
                //var v = new Vector3(0, 0, ForwardSpeed);
                //v = Vector3.Transform(v, forwardMovement);
                //avatarPosition.Z += v.Z;
                //avatarPosition.X += v.X;
                var horizontal = avatarPitch.Cos();
                var vertical = -avatarPitch.Sin();
                var v = new XVector3(avatarYaw.Sin() * horizontal, vertical, avatarYaw.Cos() * horizontal);
                v.Normalize();

                var newPos = avatarPosition + v*forwardSpeed;
                var canMove = true;
                //Ray ray;
                //if (GetRayToCursor(out ray))
                //{
                //    // collision test
                //    float dist;
                //    if (Tile.FindFirstHitTriangle(ray, out dist) != -1)
                //    {
                //        // stop moving, if we run against something
                //        canMove = dist > CollisionDistance;
                //    }
                //}
                if (canMove)
                {
                    avatarPosition = newPos;
                }
            }

            if (!IsMenuVisible
                && (keyboardState.IsKeyDown(Keys.S)
                    || (gamePadState.DPad.Down == ButtonState.Pressed)))
            {
                var forwardSpeed = ForwardSpeed;
                if (keyboardState.IsKeyDown(Keys.LeftShift) || keyboardState.IsKeyDown(Keys.RightShift))
                {
                    forwardSpeed *= walkFactor;
                }

                var horizontal = avatarPitch.Cos();
                var vertical = -avatarPitch.Sin();
                var v = new XVector3(avatarYaw.Sin() * horizontal, vertical, avatarYaw.Cos() * horizontal);
                v.Normalize();
                avatarPosition -= v*forwardSpeed;
            }

            if (!IsMenuVisible && keyboardState.IsKeyDown(Keys.F))
            {
                var forwardSpeed = ForwardSpeed;
                if (keyboardState.IsKeyDown(Keys.LeftShift) || keyboardState.IsKeyDown(Keys.RightShift))
                {
                    forwardSpeed *= walkFactor;
                }
                avatarPosition.Y = avatarPosition.Y - forwardSpeed;
            }

            if (!IsMenuVisible
                && (keyboardState.IsKeyDown(Keys.R)
                    || keyboardState.IsKeyDown(Keys.Space)))
            {
                var forwardSpeed = ForwardSpeed;
                if (keyboardState.IsKeyDown(Keys.LeftShift) || keyboardState.IsKeyDown(Keys.RightShift))
                {
                    forwardSpeed *= walkFactor;
                }
                avatarPosition.Y = avatarPosition.Y + forwardSpeed;
            }

            // adjust speed
            if (keyboardState.IsKeyDown(Keys.OemPlus))
            {
                ForwardSpeed = Math.Min(ForwardSpeed + 0.1f, 15);
            }
            else if (keyboardState.IsKeyDown(Keys.OemMinus))
            {
                ForwardSpeed = Math.Max(ForwardSpeed - 0.1f, 0.1f);
            }

            // menu
            if (keyboardState.IsKeyDown(Keys.Escape))
            {
                if (!escapeDown)
                {
                    escapeDown = true;
                    IsMenuVisible = !IsMenuVisible;
                }
            }
            else if (escapeDown)
            {
                escapeDown = false;
            }

            // highlight
            if (keyboardState.IsKeyDown(Keys.H))
            {
                HighlightSurroundings(100);
            }

            if (keyboardState.IsKeyDown(Keys.T) && TriangleSelectionRenderer.RenderingVerticies.Length > 2)
            {
                // test intersection with the first selected triangle
                var t = new Triangle(TriangleSelectionRenderer.RenderingVerticies[0].Position.ToWCell(),
                                     TriangleSelectionRenderer.RenderingVerticies[1].Position.ToWCell(),
                                     TriangleSelectionRenderer.RenderingVerticies[2].Position.ToWCell());

                Ray ray;
                GetRayToCursor(out ray);
                float distance;
                if (Intersection.RayTriangleIntersect(ray, t.Point1, t.Point2, t.Point3, out distance))
                {
                    Console.WriteLine("Hit - Distance: " + distance);
                }
                else
                {
                    Console.WriteLine("No hit");
                }
            }

            // clear
            if (keyboardState.IsKeyDown(Keys.C))
            {
                ClearSelection();
            }

            if (!IsMenuVisible
                && (keyboardState.IsKeyDown(Keys.LeftControl)
                    || keyboardState.IsKeyDown(Keys.RightControl)))
            {
                if (keyboardState.IsKeyDown(Keys.LeftAlt)
                    || keyboardState.IsKeyDown(Keys.RightAlt))
                {
                    SetEnvironmentVisibility(true);
                }
                else if (keyboardState.IsKeyDown(Keys.LeftShift)
                         || keyboardState.IsKeyDown(Keys.RightShift))
                {
                    SetEnvironmentVisibility(true);
                }
                else if (keyboardState.IsKeyDown(Keys.LeftWindows)
                         || keyboardState.IsKeyDown(Keys.RightWindows))
                {
                    SetEnvironmentVisibility(true);
                }
                else if (keyboardState.IsKeyDown(Keys.PrintScreen))
                {
                    SetEnvironmentVisibility(true);
                }
                else
                {
                    SetEnvironmentVisibility(false);
                }
            }
            else
            {
                SetEnvironmentVisibility(true);
            }

            // mouse
            if (!IsMenuVisible
                && mouseState.LeftButton == ButtonState.Pressed
                && !mouseLeftButtonDown)
            {
                // select polygon
                mouseLeftButtonDown = true;

                if (keyboardState.IsKeyDown(Keys.LeftControl))
                {
                    SelectPolygon();
                }
                else
                {
                    if (selectedPoints.Count >= 2)
                    {
                        // clear
                        ClearSelection();
                    }
                    else
                    {
                        // select a path
                        SelectOnPath();
                    }
                }
            }

            if (!IsMenuVisible
                && mouseState.LeftButton == ButtonState.Released
                && mouseLeftButtonDown)
            {
                mouseLeftButtonDown = false;
            }
        }
示例#41
0
 public void MoveForward(float amount, float deltaTime)
 {
     Vector3 frontXz = new Vector3(Front.X, 0.0f, Front.Z);
     frontXz.Normalize();
     Position += amount * new Vector3(1, 0, 1) * frontXz * deltaTime;
 }
示例#42
0
 public void MoveRight(float amount, float deltaTime)
 {
     Vector3 rightXz = new Vector3(Right.X, 0.0f, Right.Z);
     rightXz.Normalize();
     Position += amount * rightXz * deltaTime;
 }
示例#43
0
        /// <summary>
        /// Calculates if the area is visible within a camera viewport or not
        /// </summary>
        /// <param name="area">The area</param>
        /// <param name="camera">The camera to check against</param>
        /// <returns>True if the area is visible, false if not</returns>
        public bool IsAreaVisible(Area area, CameraBase camera)
        {
            if (area.Info.IsEmpty)
            {
                return false;
            }

            // Calculate the distance from the area to the camera
            areaToCameraDistance = (area.Info.Center - camera.Position).Length();

            // Is the area within stand-on or next-to distance
            if (areaToCameraDistance < areasAlwaysVisibleWithinDistance)
            {
                return true;
            }

            // Calculate the normal from the area pointing towards the camera position
            areaLookAtNormal = (camera.Position - area.Info.Center);
            areaLookAtNormal.Normalize();

            return Vector3.Dot(camera.LookAtNormal, areaLookAtNormal) <= -0.5f;
        }
示例#44
0
        void OnSimulDragHandler(OnSimulDrag msg)
        {
            if (_observer != null)
            {
                Vector2 drag = (Vector2)msg.Object;
                xnaTypes.Vector3 view = _observer.LookAt - _observer.Location;
                view.Normalize();
                xnaTypes.Vector3 up = new xnaTypes.Vector3(0, 1, 0);
                float dot = xnaTypes.Vector3.Dot(view, up);
                if (Math.Abs(dot) > 0.99)
                {
                    up += new xnaTypes.Vector3(0.1f, 0, 0);
                    up.Normalize();
                }
                xnaTypes.Vector3 right = xnaTypes.Vector3.Cross(view, up);
                view = xnaTypes.Vector3.Multiply(view, 10f);
                view = xnaTypes.Vector3.Transform(view, xnaTypes.Matrix.CreateFromAxisAngle(up, (float)(-drag.X * Math.PI / 500)));
                view = xnaTypes.Vector3.Transform(view, xnaTypes.Matrix.CreateFromAxisAngle(right, (float)(-drag.Y * Math.PI / 500)));

                _observer.LookAt = _observer.Location + view;
            }
        }
示例#45
0
        /// <summary>
        /// Extracts the local axes from the Entity's current orientation.
        /// </summary>
        private void ExtractAxes()
        {
            Matrix m = Matrix.CreateFromQuaternion(orientation);

            right = new Vector3(m.M11, m.M12, m.M13);
            right.Normalize();

            up = new Vector3(m.M21, m.M22, m.M23);
            up.Normalize();

            forward = new Vector3(-m.M31, -m.M32, -m.M33);
            forward.Normalize();
        }