利用c++实现三维图形基本变换,变换图形为正六面体,请给出示例代码
时间: 2024-03-23 14:39:38 浏览: 25
以下是一个使用C++实现三维图形基本变换的示例代码,包括平移、旋转和缩放,并将一个正六面体进行变换:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Point {
public:
float x, y, z;
Point() {
x = y = z = 0;
}
Point(float x, float y, float z) {
this->x = x;
this->y = y;
this->z = z;
}
void print() {
cout << "(" << x << ", " << y << ", " << z << ")" << endl;
}
Point operator+(const Point& p) const {
return Point(x + p.x, y + p.y, z + p.z);
}
Point operator-(const Point& p) const {
return Point(x - p.x, y - p.y, z - p.z);
}
Point operator*(float s) const {
return Point(x * s, y * s, z * s);
}
Point operator/(float s) const {
return Point(x / s, y / s, z / s);
}
Point operator*(const Point& p) const {
return Point(x * p.x, y * p.y, z * p.z);
}
Point operator/(const Point& p) const {
return Point(x / p.x, y / p.y, z / p.z);
}
};
class Cube {
public:
Point vertices[8];
Cube() {
vertices[0] = Point(-1, -1, -1);
vertices[1] = Point(1, -1, -1);
vertices[2] = Point(1, 1, -1);
vertices[3] = Point(-1, 1, -1);
vertices[4] = Point(-1, -1, 1);
vertices[5] = Point(1, -1, 1);
vertices[6] = Point(1, 1, 1);
vertices[7] = Point(-1, 1, 1);
}
void print() {
for (int i = 0; i < 8; i++) {
vertices[i].print();
}
}
void translate(float x, float y, float z) {
Point t(x, y, z);
for (int i = 0; i < 8; i++) {
vertices[i] = vertices[i] + t;
}
}
void rotateX(float angle) {
float s = sin(angle);
float c = cos(angle);
for (int i = 0; i < 8; i++) {
float y = vertices[i].y * c - vertices[i].z * s;
float z = vertices[i].y * s + vertices[i].z * c;
vertices[i].y = y;
vertices[i].z = z;
}
}
void rotateY(float angle) {
float s = sin(angle);
float c = cos(angle);
for (int i = 0; i < 8; i++) {
float x = vertices[i].x * c - vertices[i].z * s;
float z = vertices[i].x * s + vertices[i].z * c;
vertices[i].x = x;
vertices[i].z = z;
}
}
void rotateZ(float angle) {
float s = sin(angle);
float c = cos(angle);
for (int i = 0; i < 8; i++) {
float x = vertices[i].x * c - vertices[i].y * s;
float y = vertices[i].x * s + vertices[i].y * c;
vertices[i].x = x;
vertices[i].y = y;
}
}
void scale(float sx, float sy, float sz) {
Point s(sx, sy, sz);
for (int i = 0; i < 8; i++) {
vertices[i] = vertices[i] * s;
}
}
};
int main() {
Cube cube;
cube.print();
cube.translate(2, 2, 2);
cube.print();
cube.rotateX(0.5);
cube.print();
cube.rotateY(0.5);
cube.print();
cube.rotateZ(0.5);
cube.print();
cube.scale(2, 2, 2);
cube.print();
return 0;
}
```
以上代码中,我们定义了一个`Point`类表示三维空间中的点,并定义了加、减、乘、除等运算符重载,使得可以方便地对点进行计算。我们也定义了一个`Cube`类表示正六面体,并在其中实现了平移、旋转和缩放等基本变换。在`main`函数中,我们创建一个正六面体对象,并对其进行一系列变换来验证我们的实现是否正确。