C++实现Vector3

使用C++实现游戏编程中常用的向量类

在游戏编程中,经常会使用向量来描述物体在平面、空间中的位置,本文可以帮助读者完成一个功能齐全的向量类。
根据上一篇Vector2的实现,我们今天来实现一下Vector3,所有函数功能都类似,添加了叉乘操作。好了,废话不多说,直接上代码。

首先是构造函数:

Vector3() :x(0), y(0), z(0) {
     }
Vector3(float _x, float _y, float _z) :x(_x), y(_y), z(_z) {
     }
explicit Vector3(float value) :x(value), y(value), z(value) {
     }
Vector3(const Vector3& other) :x(other.x), y(other.y), z(other.z) {
     }

//other construct support
Vector3(const Vector2& other) :x(other.x), y(other.y), z(0) {
     }
Vector3(const Vector2& other, float value) :x(other.x), y(other.
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
C++中,Vector3通常是指三维向量,它可以用来表示三维空间中的位置、方向、速度等。通常情况下,我们可以使用结构体或类来实现Vector3。 以下是一个使用结构体实现Vector3的例子: ```c++ struct Vector3 { float x, y, z; Vector3(float x = 0, float y = 0, float z = 0) : x(x), y(y), z(z) {} Vector3 operator+(const Vector3& v) const { return Vector3(x + v.x, y + v.y, z + v.z); } Vector3 operator-(const Vector3& v) const { return Vector3(x - v.x, y - v.y, z - v.z); } Vector3 operator*(float s) const { return Vector3(x * s, y * s, z * s); } Vector3 operator/(float s) const { return Vector3(x / s, y / s, z / s); } float dot(const Vector3& v) const { return x * v.x + y * v.y + z * v.z; } Vector3 cross(const Vector3& v) const { return Vector3(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x); } float length() const { return sqrt(x * x + y * y + z * z); } Vector3 normalize() const { return *this / length(); } }; ``` 以上代码定义了一个Vector3结构体,包含了向量的x、y、z三个分量,以及一些常用的向量运算,例如加减乘除、点积、叉积、长度、归一化等。 以下是一个使用类实现Vector3的例子: ```c++ class Vector3 { public: float x, y, z; Vector3(float x = 0, float y = 0, float z = 0) : x(x), y(y), z(z) {} Vector3 operator+(const Vector3& v) const { return Vector3(x + v.x, y + v.y, z + v.z); } Vector3 operator-(const Vector3& v) const { return Vector3(x - v.x, y - v.y, z - v.z); } Vector3 operator*(float s) const { return Vector3(x * s, y * s, z * s); } Vector3 operator/(float s) const { return Vector3(x / s, y / s, z / s); } float dot(const Vector3& v) const { return x * v.x + y * v.y + z * v.z; } Vector3 cross(const Vector3& v) const { return Vector3(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x); } float length() const { return sqrt(x * x + y * y + z * z); } Vector3 normalize() const { return *this / length(); } }; ``` 以上代码定义了一个Vector3类,与结构体实现的例子类似,不同之处在于使用了类的封装特性,将成员变量和成员函数分别定义在了public和private中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值