在三维空间中移动图像

2 投票
1 回答
1754 浏览
提问于 2025-04-17 03:50

我正在尝试用Python创建一个logo的可视化效果,想要在3D空间中动画化一些图片,让这些图片始终“面向”屏幕的中心,并且在某个固定的路径上移动。我之前用过Vizard实现过这个效果,不过这次我想用一种“自由”的方式,并且希望它能在不同的平台上都能运行。

请问,使用pyglet,怎样才能用最少的代码快速获取一个可以操作位置和方向的图片映射四边形呢?

1 个回答

6

下面是我能想到的最简单的代码,它让我把图像放在了位置 (0, 0, -10):

#!/usr/bin/env python                                                           
import pyglet
from pyglet.gl import *

window = pyglet.window.Window()
glEnable(GL_DEPTH_TEST)

image = pyglet.image.load('imgs/appfolio.png')
texture = image.get_texture()
glEnable(texture.target)
glBindTexture(texture.target, texture.id)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height,
             0, GL_RGBA, GL_UNSIGNED_BYTE,
             image.get_image_data().get_data('RGBA', image.width * 4))

rect_w = float(image.width) / image.height
rect_h = 1

@window.event
def on_draw():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    glTranslatef(0, 0, -10)
    glBindTexture(texture.target, texture.id)
    glBegin(GL_QUADS)
    glTexCoord2f(0.0, 0.0); glVertex3f(-rect_w, -rect_h, 0.0)
    glTexCoord2f(1.0, 0.0); glVertex3f( rect_w, -rect_h, 0.0)
    glTexCoord2f(1.0, 1.0); glVertex3f( rect_w,  rect_h, 0.0)
    glTexCoord2f(0.0, 1.0); glVertex3f(-rect_w,  rect_h, 0.0)
    glEnd()

def on_resize(width, height):
    glViewport(0, 0, width, height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(65.0, width/float(height), 0.1, 1000.0)
    glMatrixMode(GL_MODELVIEW)

window.on_resize = on_resize # we need to replace so can't use @window.event    
pyglet.app.run()

我发现最难的部分是需要替换 on_resize 函数,这样它才能按我预期的方式工作,因为默认的正交投影并不好用。

我发现 Jess Hill 的 pyglet 转换,是对 NeHe 关于纹理映射的教程 的一个很有帮助的参考。

完整的 logo 可视化代码可以在我刚写的一篇博客文章中找到,标题是 "用 Pyglet 在 3D 空间中移动图像"。

撰写回答