Jac*_*row 1 python opengl pyglet python-2.7
我正在尝试创建一个围绕鼠标拖动形成的正方形(例如,在桌面上拖动时出现的正方形).这是我尝试过的代码:
import pyglet
from pyglet.window import mouse
window = pyglet.window.Window()
@window.event
def on_draw():
    window.clear()
@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, ('v2f', [x, y, dx, y, dx, dy, x, dy]))
pyglet.app.run()
但是,它不起作用,我不明白为什么.有什么建议?
我从您的解决方案开始并对其进行了一些改进。通过添加 on_draw 函数来修复矩形伪影问题,在该函数中您可以清除窗口,然后重新绘制每个对象。Pyglet (OpenGL) 使用双缓冲,所以这比听起来要快得多。
import pyglet
# rectangle class
class Rect:
  def __init__(self, x, y, w, h):
    self.set(x, y, w, h)
  def draw(self):
    pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, self._quad)
  def set(self, x=None, y=None, w=None, h=None):
    self._x = self._x if x is None else x
    self._y = self._y if y is None else y
    self._w = self._w if w is None else w
    self._h = self._h if h is None else h
    self._quad = ('v2f', (self._x, self._y,
                          self._x + self._w, self._y,
                          self._x + self._w, self._y + self._h,
                          self._x, self._y + self._h))
  def __repr__(self):
    return f"Rect(x={self._x}, y={self._y}, w={self._w}, h={self._h})"
# main function
def main():
  r1 = Rect(10, 10, 100, 100)
  window = pyglet.window.Window()
  @window.event
  def on_draw():
    window.clear()
    r1.draw()
  @window.event
  def on_mouse_press(x, y, button, modifiers):
    r1.set(x=x, y=y)
    print(r1)
  @window.event
  def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    r1.set(x=x, y=y)
    print(r1)
  pyglet.app.run()
if __name__ == '__main__':
  main()
所以,由于没有答案,这就是我解决问题的方法:
import pyglet
from pyglet.window import mouse
window = pyglet.window.Window()
@window.event
def on_draw():
    pass
@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, ('v2f', [x, y, x-dx, y, x-dx, y-dy, x, y-dy]))
    print x, y, dx, y, dx, dy, x, dy
pyglet.app.run()
现在我只需要弄清楚如何破坏矩形......
| 归档时间: | 
 | 
| 查看次数: | 4979 次 | 
| 最近记录: |