⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dxmutmisc.cs

📁 运用directX完成的坦克游戏雏形
💻 CS
📖 第 1 页 / 共 5 页
字号:
        /// </summary>
        public void OnMove(int x, int y)
        {
            if (isDragging)
            {
                currentPt = ScreenToVector((float)x, (float)y);
                nowQuat = downQuat * QuaternionFromBallPoints(downPt, currentPt);
            }
        }
        /// <summary>
        /// Done dragging the arcball
        /// </summary>
        public void OnEnd()
        {
            isDragging = false;
        }

        /// <summary>
        /// Handle messages from the window
        /// </summary>
        public bool HandleMessages(IntPtr hWnd, NativeMethods.WindowMessage msg, IntPtr wParam, IntPtr lParam)
        {
            // Current mouse position
            short mouseX = NativeMethods.LoWord((uint)lParam.ToInt32());
            short mouseY = NativeMethods.HiWord((uint)lParam.ToInt32());

            switch(msg)
            {
                case NativeMethods.WindowMessage.LeftButtonDown:
                case NativeMethods.WindowMessage.LeftButtonDoubleClick:
                    // Set capture
                    NativeMethods.SetCapture(hWnd);
                    OnBegin(mouseX, mouseY);
                    return true;
                case NativeMethods.WindowMessage.LeftButtonUp:
                    // Release capture
                    NativeMethods.ReleaseCapture();
                    OnEnd();
                    return true;

                case NativeMethods.WindowMessage.RightButtonDown:
                case NativeMethods.WindowMessage.RightButtonDoubleClick:
                case NativeMethods.WindowMessage.MiddleButtonDown:
                case NativeMethods.WindowMessage.MiddleButtonDoubleClick:
                    // Set capture
                    NativeMethods.SetCapture(hWnd);
                    // Store off the position of the cursor
                    lastMousePosition = new System.Drawing.Point(mouseX, mouseY);
                    return true;

                case NativeMethods.WindowMessage.RightButtonUp:
                case NativeMethods.WindowMessage.MiddleButtonUp:
                    // Release capture
                    NativeMethods.ReleaseCapture();
                    return true;

                case NativeMethods.WindowMessage.MouseMove:
                    short buttonState = NativeMethods.LoWord((uint)wParam.ToInt32());
                    bool leftButton = ((buttonState & (short)NativeMethods.MouseButtons.Left) != 0);
                    bool rightButton = ((buttonState & (short)NativeMethods.MouseButtons.Right) != 0);
                    bool middleButton = ((buttonState & (short)NativeMethods.MouseButtons.Middle) != 0);

                    if (leftButton)
                    {
                        OnMove(mouseX, mouseY);
                    }
                    else if (rightButton || middleButton)
                    {
                        // Normalize based on size of window and bounding sphere radius
                        float deltaX = (lastMousePosition.X - mouseX) * radiusTranslation / width;
                        float deltaY = (lastMousePosition.Y - mouseY) * radiusTranslation / height;

                        if (rightButton)
                        {
                            translationDelta = Matrix.Translation(-2*deltaX,2*deltaY, 0.0f);
                            translation *= translationDelta;
                        }
                        else // Middle button
                        {
                            translationDelta = Matrix.Translation(0.0f, 0.0f, 5*deltaY);
                            translation *= translationDelta;
                        }
                        // Store off the position of the cursor
                        lastMousePosition = new System.Drawing.Point(mouseX, mouseY);
                    }
                    return true;
            }

            return false;
        }
    }
    #endregion

    #region Cameras
    /// <summary>
    /// Used to map keys to the camera
    /// </summary>
    public enum CameraKeys : byte
    {
        StrafeLeft,
        StrafeRight,
        MoveForward,
        MoveBackward,
        MoveUp,
        MoveDown,
        Reset,
        ControlDown,
        MaxKeys,
        Unknown=0xff
    }

    /// <summary>
    /// Mouse button mask values
    /// </summary>
    [Flags]
    public enum MouseButtonMask : byte
    {
        None = 0,
        Left = 0x01,
        Middle = 0x02,
        Right = 0x04,
        Wheel = 0x08,
    }

    /// <summary>
    /// Simple base camera class that moves and rotates.  The base class
    /// records mouse and keyboard input for use by a derived class, and 
    /// keeps common state.
    /// </summary>
    public abstract class Camera
    {
        /// <summary>
        /// Maps NativeMethods.WindowMessage.Key* msg to a camera key
        /// </summary>
        protected static CameraKeys MapKey(IntPtr param)
        {
            System.Windows.Forms.Keys key = (System.Windows.Forms.Keys)param.ToInt32();
            switch(key)
            {
                case System.Windows.Forms.Keys.ControlKey: return CameraKeys.ControlDown;
                case System.Windows.Forms.Keys.Left: return CameraKeys.StrafeLeft;
                case System.Windows.Forms.Keys.Right: return CameraKeys.StrafeRight;
                case System.Windows.Forms.Keys.Up: return CameraKeys.MoveForward;
                case System.Windows.Forms.Keys.Down: return CameraKeys.MoveBackward;
                case System.Windows.Forms.Keys.Prior: return CameraKeys.MoveUp; // pgup
                case System.Windows.Forms.Keys.Next: return CameraKeys.MoveDown; // pgdn

                case System.Windows.Forms.Keys.A: return CameraKeys.StrafeLeft;
                case System.Windows.Forms.Keys.D: return CameraKeys.StrafeRight;
                case System.Windows.Forms.Keys.W: return CameraKeys.MoveForward;
                case System.Windows.Forms.Keys.S: return CameraKeys.MoveBackward;
                case System.Windows.Forms.Keys.Q: return CameraKeys.MoveUp; 
                case System.Windows.Forms.Keys.E: return CameraKeys.MoveDown; 

                case System.Windows.Forms.Keys.NumPad4: return CameraKeys.StrafeLeft;
                case System.Windows.Forms.Keys.NumPad6: return CameraKeys.StrafeRight;
                case System.Windows.Forms.Keys.NumPad8: return CameraKeys.MoveForward;
                case System.Windows.Forms.Keys.NumPad2: return CameraKeys.MoveBackward;
                case System.Windows.Forms.Keys.NumPad9: return CameraKeys.MoveUp; 
                case System.Windows.Forms.Keys.NumPad3: return CameraKeys.MoveDown; 

                case System.Windows.Forms.Keys.Home: return CameraKeys.Reset; 
            }
            // No idea
            return (CameraKeys)byte.MaxValue;
        }


        #region Instance Data
        protected Matrix viewMatrix; // View Matrix
        protected Matrix projMatrix; // Projection matrix

        protected System.Drawing.Point lastMousePosition;  // Last absolute position of mouse cursor
        protected bool isMouseLButtonDown;    // True if left button is down 
        protected bool isMouseMButtonDown;    // True if middle button is down 
        protected bool isMouseRButtonDown;    // True if right button is down 
        protected int currentButtonMask;   // mask of which buttons are down
        protected int mouseWheelDelta;     // Amount of middle wheel scroll (+/-) 
        protected Vector2 mouseDelta;          // Mouse relative delta smoothed over a few frames
        protected float framesToSmoothMouseData; // Number of frames to smooth mouse data over

        protected Vector3 defaultEye;          // Default camera eye position
        protected Vector3 defaultLookAt;       // Default LookAt position
        protected Vector3 eye;                 // Camera eye position
        protected Vector3 lookAt;              // LookAt position
        protected float cameraYawAngle;      // Yaw angle of camera
        protected float cameraPitchAngle;    // Pitch angle of camera

        protected System.Drawing.Rectangle dragRectangle; // Rectangle within which a drag can be initiated.
        protected Vector3 velocity;            // Velocity of camera
        protected bool isMovementDrag;        // If true, then camera movement will slow to a stop otherwise movement is instant
        protected Vector3 velocityDrag;        // Velocity drag force
        protected float dragTimer;           // Countdown timer to apply drag
        protected float totalDragTimeToZero; // Time it takes for velocity to go from full to 0
        protected Vector2 rotationVelocity;         // Velocity of camera

        protected float fieldOfView;                 // Field of view
        protected float aspectRatio;              // Aspect ratio
        protected float nearPlane;           // Near plane
        protected float farPlane;            // Far plane

        protected float rotationScaler;      // Scaler for rotation
        protected float moveScaler;          // Scaler for movement

        protected bool isInvertPitch;         // Invert the pitch axis
        protected bool isEnablePositionMovement; // If true, then the user can translate the camera/model 
        protected bool isEnableYAxisMovement; // If true, then camera can move in the y-axis

        protected bool isClipToBoundary;      // If true, then the camera will be clipped to the boundary
        protected Vector3 minBoundary;         // Min point in clip boundary
        protected Vector3 maxBoundary;         // Max point in clip boundary

        protected bool isResetCursorAfterMove;// If true, the class will reset the cursor position so that the cursor always has space to move 

        // State of the input
        protected bool[] keys;
        public static readonly Vector3 UpDirection = new Vector3(0,1,0);
        #endregion

        #region Simple Properties
        /// <summary>Is the camera being 'dragged' at all?</summary>
        public bool IsBeingDragged { get { return (isMouseLButtonDown || isMouseMButtonDown || isMouseRButtonDown); } }
        /// <summary>Is the left mouse button down</summary>
        public bool IsMouseLeftButtonDown { get { return isMouseLButtonDown; } }
        /// <summary>Is the right mouse button down</summary>
        public bool IsMouseRightButtonDown { get { return isMouseRButtonDown; } }
        /// <summary>Is the middle mouse button down</summary>
        public bool IsMouseMiddleButtonDown { get { return isMouseMButtonDown; } }
        /// <summary>Returns the view transformation matrix</summary>
        public Matrix ViewMatrix { get { return viewMatrix; } }
        /// <summary>Returns the projection transformation matrix</summary>
        public Matrix ProjectionMatrix { get { return projMatrix; } }
        /// <summary>Returns the location of the eye</summary>
        public Vector3 EyeLocation { get { return eye; } }
        /// <summary>Returns the look at point of the camera</summary>
        public Vector3 LookAtPoint { get { return lookAt; } }
        /// <summary>Is position movement enabled</summary>
        public bool IsPositionMovementEnabled { get {return isEnablePositionMovement; } set { isEnablePositionMovement = value; } }
        #endregion
        
        /// <summary>
        /// Abstract method to control camera during frame move
        /// </summary>
        public abstract void FrameMove(float elapsedTime);

        /// <summary>
        /// Constructor for the base camera class (Sets up camera defaults)
        /// </summary>
        protected Camera()
        {
            // Create the keys
            keys = new bool[(int)CameraKeys.MaxKeys];

            // Set attributes for the view matrix
            eye = Vector3.Empty;
            lookAt = new Vector3(0.0f, 0.0f, 1.0f);

            // Setup the view matrix
            SetViewParameters(eye, lookAt);

            // Setup the projection matrix
            SetProjectionParameters((float)Math.PI / 4, 1.0f, 1.0f, 1000.0f);

            // Store mouse information
            lastMousePosition = System.Windows.Forms.Cursor.Position;
            isMouseLButtonDown = false;
            isMouseRButtonDown = false;
            isMouseMButtonDown = false;
            mouseWheelDelta = 0;
            currentButtonMask = 0;

            // Setup camera rotations
            cameraYawAngle = 0.0f;
            cameraPitchAngle = 0.0f;

            dragRectangle = new System.Drawing.Rectangle(0, 0, int.MaxValue, int.MaxValue);
            velocity = Vector3.Empty;
            isMovementDrag = false;
            velocityDrag = Vector3.Empty;
            dragTimer = 0.0f;
            totalDragTimeToZero = 0.25f;
            rotationVelocity = Vector2.Empty;
            rotationScaler = 0.1f;
            moveScaler = 5.0f;
            isInvertPitch = false;
            isEnableYAxisMovement = true;
            isEnablePositionMovement = true;
            mouseDelta = Vector2.Empty;
            framesToSmoothMouseData = 2.0f;
            isClipToBoundary = false;
            minBoundary = new Vector3(-1.0f,-1.0f, -1.0f);
            maxBoundary = new Vector3(1,1,1);
            isResetCursorAfterMove = false;
        }

        /// <summary>
        /// Call this from your message proc so this class can handle window messages
        /// </summary>
        public virtual bool HandleMessages(IntPtr hWnd, NativeMethods.WindowMessage msg, IntPtr wParam, IntPtr lParam)
        {
            switch(msg)
            {
                // Handle the keyboard
                case NativeMethods.WindowMessage.KeyDown:
                    CameraKeys mappedKeyDown = MapKey(wParam);
                    if (mappedKeyDown != (CameraKeys)byte.MaxValue)
                    {
                        // Valid key was pressed, mark it as 'down'
                        keys[(int)mappedKeyDown] = true;
                    }
                    break;
                case NativeMethods.WindowMessage.KeyUp:
                    CameraKeys mappedKeyUp = MapKey(wParam);
                    if (mappedKeyUp != (CameraKeys)byte.MaxValue)
                    {
                        // Valid key was let go, mark it as 'up'
                        keys[(int)mappedKeyUp] = false;
                    }
                    break;

                // Handle the mouse
                case NativeMethods.WindowMessage.LeftButtonDoubleClick:

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -