[Unity] 3D數學基礎 - 2D旋轉矩陣


2D矩陣的旋轉:

 

NewX = X * Cos(α) - Y * Sin(α)

NewY = X * Sin(α) + Y * Cos(α)

 

一般在三角函數中使用的是弧度,我們可以通過下面的公式將角度轉為弧度:

α = (degrees / 360 * PI)

 

 

示例代碼:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace MatrixTransForm
{
    /// <summary>
    /// 三角形
    /// </summary>
    class Triangle
    {
        PointF A, B, C;

        public Triangle(PointF A, PointF B, PointF C)
        {
            this.A = A;
            this.B = B;
            this.C = C;
        }

        /// <summary>
        /// 繪制三角形
        /// </summary>
        /// <param name="g"></param>
        public void Draw(Graphics g)
        {
            Pen pen = new Pen(Color.Red);
            pen.Width = 4;
            g.DrawLine(pen, A, B);
            g.DrawLine(pen, B, C);
            g.DrawLine(pen, C, A);
        }


        /// <summary>
        /// 旋轉三角形
        /// </summary>
        /// <param name="degrees">要旋轉的角度</param>
        public void Rotate(int degrees)
        {
            // 將角度轉為弧度
            float angle = (float)(degrees / 360.0f * Math.PI);

            float newX = (float)(A.X * Math.Cos(angle) - A.Y * Math.Sin(angle));
            float newY = (float)(A.X * Math.Sin(angle) + A.Y * Math.Cos(angle));

            A.X = newX;
            A.Y = newY;

            newX = (float)(B.X * Math.Cos(angle) - B.Y * Math.Sin(angle));
            newY = (float)(B.X * Math.Sin(angle) + B.Y * Math.Cos(angle));

            B.X = newX;
            B.Y = newY;

            newX = (float)(C.X * Math.Cos(angle) - C.Y * Math.Sin(angle));
            newY = (float)(C.X * Math.Sin(angle) + C.Y * Math.Cos(angle));

            C.X = newX;
            C.Y = newY;

        }
    }
}

 

窗口代碼:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MatrixTransForm
{
    public partial class Form1 : Form
    {
        Triangle t;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (t == null)
                t = new Triangle(new PointF(0, -100), new PointF(100, 100), new PointF(-100, 100));
            Invalidate();
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            if (t != null)
            {
                e.Graphics.TranslateTransform(200, 200);
                t.Draw(e.Graphics);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (t != null)
            {
                t.Rotate(1);
                Invalidate();
            }
        }
    }
}

 

效果:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM