这一篇接着来一步步实现。
本篇主要是介绍向量,然后利用C++实现它(先实现二维向量,往后会进一步实现三维向量),并通过今天实现的东西,做一个小游戏(鼠标点选位置,人物朝目标位置移动)
1.首先是实现二维向量:vector2.h
理论:
#pragma once
#include <cmath>
#include <cassert>
//二维向量:没有叉乘cross
class Vector2
{
public:
float x;
float y;
//构造
Vector2(float _x = 0.0f, float _y = 0.0f):x(_x),y(_y){}
void Set(float _x = 0.0f, float _y = 0.0f)
{
x = _x;
y = _y;
}
//负号重载
Vector2 operator - () const
{
return Vector2(-x, -y);
}
//向量相等判定重载
BOOL IsEqual(const Vector2& that) const
{
if (x == that.x && y == that.y)
return true;
return false;
}
//向量加法
Vector2 operator + (const Vector2 &that) const
{
return Vector2(x + that.x, y + that.y);
}
Vector2& operator += (const Vector2& that)
{
x += that.x;
y += that.y;
return *this;
}
//向量减法
Vector2 operator - (const Vector2& that) const
{
return Vector2(x - that.x, y - that.y);
}
Vector2& operator -= (const Vector2& that)
{
x -= that.x;
y -= that.y;
return *this;
}
//向量乘标量
Vector2 operator * (float t) const
{
return Vector2(x * t, y * t);
}
Vector2& operator *= (float t)
{
x *= t;
y *= t;
return *this;
}
//向量除标量
Vector2 operator / (float t) const
{
//断言非零
assert(!(t >= -0.0