[Python] When I try to move the camera forward the object rotates

Discussão em 'Python' iniciado por Stack, Março 15, 2025.

  1. Stack

    Stack Membro Participativo

    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
    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
    tempY.append(item)
    tempY.append(y[i1])
    update(tempX,tempY)


    The file(s), 'monkey.obj' is located at https://github.com/CHARSARG/MatPlotRenderer because it's to large.

    I've posted an answer, which resolves the issue, but I still don't understand why the function wasn't working. Please edit my answer, or post a new answer if you can explain the issue.

    Continue reading...

Compartilhe esta Página