まずは練習用に2×2の行列クラス
行列クラスを自分で作ってみる。
まずは前提知識無しで作った最初のバージョンを公開
#include "vector2.h" namespace ddp { class Matrix2 { public: Vector2 v1; Vector2 v2; Matrix2(Vector2 v1,Vector2 v2) { this->v1 = v1; this->v2 = v2; } // ベクトルを行列に変換(必要かどうか微妙) Matrix2(Vector2 v) { this->v1.x = v.x; this->v1.y = 0.0f; this->v2.x = 0.0f; this->v2.y = v.y; } // コピーコンストラクタ Matrix2(const Matrix2 &mat) { this->v1 = mat.v1; this->v2 = mat.v2; } // 行列同士の掛け算 Matrix2 operator*(const Matrix2 &mat) const { return Matrix2( Vector2( v1.x * mat.v1.x + v1.y * mat.v2.x, v1.x * mat.v1.y + v1.y * mat.v2.y ), Vector2( v2.x * mat.v1.x + v2.y * mat.v2.x, v2.x * mat.v1.y + v2.y * mat.v2.y ) ); } Matrix2& operator*=(const Matrix2 &mat) { float v1x = v1.x * mat.v1.x + v1.y * mat.v2.x; float v1y = v1.x * mat.v1.y + v1.y * mat.v2.y; float v2x = v2.x * mat.v1.x + v2.y * mat.v2.x; float v2y = v2.x * mat.v1.y + v2.y * mat.v2.y; v1.x = v1x; v1.y = v1y; v2.x = v2x; v2.y = v2y; return *this; } // スカラの掛け算 Matrix2 operator*(float s) const { return Matrix2( Vector2(v1.x*s,v1.y*s), Vector2(v2.x*s,v2.y*s) ); } Matrix2& operator*=(float s) { v1.x *= s; v1.y *= s; v2.x *= s; v2.y *= s; return *this; } // 行列の転置 Matrix2 operator!() const { return Matrix2( Vector2(v1.x,v2.x), Vector2(v1.y,v2.y) ); } // 全て足したベクトルを返す Vector2 vector() const { return v1 + v2; } }; };
vector2.hは先日自分で作ったベクトルクラスです。
さてこの行列クラス。とても扱いにくい。やはりベクトルで持たないほうが良さそうだ。どうもfloat型の配列の方が一般的っぽい。
また、この実装では回転とスケーリングしか表現できない。
ということで次回はもっとマシな実装の行列クラスを作ってみることにする。