Skip to content

Instantly share code, notes, and snippets.

@secemp9
Created November 27, 2024 15:11
Show Gist options
  • Save secemp9/bb64ad92dfffa6cbd950a829fefc4b03 to your computer and use it in GitHub Desktop.
Save secemp9/bb64ad92dfffa6cbd950a829fefc4b03 to your computer and use it in GitHub Desktop.
rotating cube
#include <TFT_eSPI.h>
#include <SPI.h>
TFT_eSPI tft = TFT_eSPI();
// 3D coordinates for cube vertices
const float vertices[8][3] = {
{-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1},
{-1, -1, 1}, {1, -1, 1}, {1, 1, 1}, {-1, 1, 1}
};
// Edges connecting vertices
const uint8_t edges[12][2] = {
{0,1}, {1,2}, {2,3}, {3,0},
{4,5}, {5,6}, {6,7}, {7,4},
{0,4}, {1,5}, {2,6}, {3,7}
};
// Display dimensions
const int centerX = 120; // Half of 240
const int centerY = 135; // Half of 270
const float scale = 40.0;
float angleX = 0;
float angleY = 0;
float angleZ = 0;
void setup() {
tft.init();
tft.setRotation(0);
tft.fillScreen(TFT_BLACK);
}
// Rotate point around X axis
void rotateX(float& y, float& z, float angle) {
float y1 = y * cos(angle) - z * sin(angle);
float z1 = y * sin(angle) + z * cos(angle);
y = y1;
z = z1;
}
// Rotate point around Y axis
void rotateY(float& x, float& z, float angle) {
float x1 = x * cos(angle) - z * sin(angle);
float z1 = x * sin(angle) + z * cos(angle);
x = x1;
z = z1;
}
// Rotate point around Z axis
void rotateZ(float& x, float& y, float angle) {
float x1 = x * cos(angle) - y * sin(angle);
float y1 = x * sin(angle) + y * cos(angle);
x = x1;
y = y1;
}
void drawCube() {
float projected[8][2]; // 2D coordinates
// Project each vertex
for(int i = 0; i < 8; i++) {
float x = vertices[i][0];
float y = vertices[i][1];
float z = vertices[i][2];
// Apply rotations
rotateX(y, z, angleX);
rotateY(x, z, angleY);
rotateZ(x, y, angleZ);
// Project 3D to 2D
float distance = 4; // Distance from viewer to screen
float z_factor = 1 / (distance - z);
// Scale and translate to screen coordinates
projected[i][0] = centerX + (x * z_factor * scale);
projected[i][1] = centerY + (y * z_factor * scale);
}
// Clear screen
tft.fillScreen(TFT_BLACK);
// Draw edges
for(int i = 0; i < 12; i++) {
tft.drawLine(
projected[edges[i][0]][0], projected[edges[i][0]][1],
projected[edges[i][1]][0], projected[edges[i][1]][1],
TFT_WHITE
);
}
}
void loop() {
// Update rotation angles
angleX += 0.03;
angleY += 0.02;
angleZ += 0.01;
drawCube();
delay(30); // Control animation speed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment