0

In my 3D renderer with Matplotlib, when I try to move the camera forward, the object rotates:

import matplotlib.pyplot as plt
import numpy as np
import math
import GetPolyData as poly


def project_3d_to_2d(x, y, z, d):
    # Calculate the angle of projection
    theta = math.atan2(z, d)

    # Calculate the projected x and y coordinates
    projected_x = x * math.cos(theta) - y * math.sin(theta)
    projected_y = x * math.sin(theta) + y * math.cos(theta)

    return projected_x, projected_y

def Project_Polygon(polygon,d,cam):
    CamX = cam[0]
    CamY = cam[1]
    CamZ = cam[2]
    X = []
    Y = []
    for point in polygon:
        x = (point[0]-CamX)
        y = (point[1]-CamY)
        z = (point[2]-CamZ)
        X1,Y1=(project_3d_to_2d(x,y,z,d))
        #print(X1,Y1)
        X.append(X1)
        Y.append(Y1)
    return X,Y

def Render(polygons,d,cam):
    x=[]
    y=[]
    for polygon in polygons:
        if not Polygon_Behind_Camera:
            pass
        else:
            X,Y = Project_Polygon(polygon,d,cam)
            #print(x,y)
            for item in X:
                x.append(item)
            for item in Y:
                y.append(item)
    return x,y

# Initial render:
model_name = 'monkey.obj'
polygons = poly.extract_polygons_from_obj(model_name)
d = 100
cam = [0,0,0,0,0]
x,y = Render(polygons,d,cam)

# Start display:
plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
display, = ax.plot(x, y, 'b-')

# Main loop:
phase = 0
while True:
    phase +=1
    print(phase)
    cam[2] = phase
    angle = (cam[3],cam[4])
    temp_polygons = polygons
    #temp_polygons = rotate_polygons(polygons,cam,angle)

    #Prject 3d to 2d
    x,y = Render(temp_polygons,d,cam)

    #Add the last verticie 1 to the end of every 3 verticies.
    tempX = []
    tempY = []
    for i1 in range(int(len(x)/3)):
        for i2 in range(3):
            i = i1+i2
            item = x[i]
            tempX.append(item)
        tempX.append(x[i1])
    for i1 in range(int(len(y)/3)):
        for i2 in range(3):
            i = i1+i2
            item = y[i]
            tempY.append(item)
        tempY.append(y[i1])
    update(tempX,tempY)
user4157124
  • 2,809
  • 13
  • 27
  • 42
charsarg
  • 61
  • 3
  • If we can't copy, paste, and run, the code, then the question doesn't contain a complete [mre]. Please review #3 of [Creating Effective Stack Overflow Questions](https://trenton3983.github.io/files/Creating_Effective_StackOverflow_Questions.html). If you must share a file, share it on a free GitHub account, – Trenton McKinney Sep 02 '23 at 17:53

0 Answers0