Skip to content

Instantly share code, notes, and snippets.

@MBlore
Created March 5, 2023 13:45
Show Gist options
  • Save MBlore/9b22e21fab9e86e624a04901663b57cd to your computer and use it in GitHub Desktop.
Save MBlore/9b22e21fab9e86e624a04901663b57cd to your computer and use it in GitHub Desktop.
3D Cube PyGame
import pygame
import math
pygame.init()
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Set the dimensions of the window
size = (800, 600)
screen = pygame.display.set_mode(size)
# Set the caption of the window
pygame.display.set_caption("Spinning 3D Cube")
# Define the vertices of the cube
vertices = [
[-1, 1, -1],
[1, 1, -1],
[1, -1, -1],
[-1, -1, -1],
[-1, 1, 1],
[1, 1, 1],
[1, -1, 1],
[-1, -1, 1]
]
# Define the edges of the cube
edges = [
(0,1),
(1,2),
(2,3),
(3,0),
(4,5),
(5,6),
(6,7),
(7,4),
(0,4),
(1,5),
(2,6),
(3,7)
]
# Define the angle of rotation
theta = 0
# Set the clock
clock = pygame.time.Clock()
# Loop until the user clicks the close button
done = False
while not done:
# Check for events
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Clear the screen
screen.fill(BLACK)
# Define the rotation matrix
cos = math.cos(theta)
sin = math.sin(theta)
rotation_matrix = [
[cos, 0, sin],
[0, 1, 0],
[-sin, 0, cos]
]
# Rotate each vertex using the rotation matrix
rotated_vertices = []
for vertex in vertices:
x = vertex[0] * rotation_matrix[0][0] + vertex[1] * rotation_matrix[0][1] + vertex[2] * rotation_matrix[0][2]
y = vertex[0] * rotation_matrix[1][0] + vertex[1] * rotation_matrix[1][1] + vertex[2] * rotation_matrix[1][2]
z = vertex[0] * rotation_matrix[2][0] + vertex[1] * rotation_matrix[2][1] + vertex[2] * rotation_matrix[2][2]
rotated_vertices.append([x, y, z])
# Project each vertex onto the 2D screen
projected_vertices = []
for vertex in rotated_vertices:
x = int(vertex[0] * 1000 / (vertex[2] + 10)) + size[0] // 2
y = int(vertex[1] * 1000 / (vertex[2] + 10)) + size[1] // 2
projected_vertices.append([x, y])
# Draw the edges of the cube
for edge in edges:
pygame.draw.line(screen, WHITE, projected_vertices[edge[0]], projected_vertices[edge[1]])
# Update the angle of rotation
theta += 0.01
# Update the screen
pygame.display.flip()
# Set the framerate
clock.tick(60)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment