Given that so far I have always used Pygame, I wanted to start using Pyglet, to understand a little how it works.
import pyglet, os
class runGame():
widthDisplay = 1024
heightDiplay = 576
title = "Pokémon Life and Death: Esploratori del proprio Destino"
wra = pyglet.image.load("wra.png")
wrb = pyglet.image.load("wrb.png")
def __init__(self):
platform = pyglet.window.get_platform()
display = platform.get_default_display()
screen = display.get_default_screen()
self.widthScreen = screen.width
self.heightScreen = screen.height
self.xDisplay = int(self.widthScreen / 2 - self.widthDisplay / 2)
self.yDisplay = int(self.heightScreen / 2 - self.heightDiplay / 2)
self.Display = pyglet.window.Window(width=self.widthDisplay, height=self.heightDiplay, caption=self.title, resizable=False)
self.Display.set_location(self.xDisplay, self.yDisplay)
pyglet.app.run()
game = runGame()
Up to here everything is fine and everything works correctly. But I was wrong, in the sense, now that I have to draw something, how should I do? In the sense, can Pyglet stay in a class like Pygame or not?
The marked solution might solve the problem.
However, in my opinion it doesn't really add more functionality than you can already achieve.
If you truly want to make Pyglet into a class, you actually gotta inherit something, or make use of the possibility of programming in a OOP way i recon.
Here's my two cents:
import pyglet
from pyglet.gl import *
from collections import OrderedDict
from time import time
key = pyglet.window.key
class main(pyglet.window.Window):
def __init__ (self, width=1024, height=576, caption="Pokémon Life and Death: Esploratori del proprio Destino", fps=True, *args, **kwargs):
super(main, self).__init__(width, height, *args, **kwargs)
platform = pyglet.window.get_platform()
display = platform.get_default_display()
screen = display.get_default_screen()
self.xDisplay = int(screen.width / 2 - self.width / 2)
self.yDisplay = int(screen.height / 2 - self.height / 2)
self.set_location(self.xDisplay, self.yDisplay)
self.sprites = OrderedDict()
if fps:
self.sprites['fps_label'] = pyglet.text.Label('0 fps', x=10, y=10)
self.last_update = time()
self.fps_count = 0
self.keys = OrderedDict()
self.mouse_x = 0
self.mouse_y = 0
self.alive = 1
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def on_mouse_motion(self, x, y, dx, dy):
self.mouse_x = x
self.mouse_y = y
def on_mouse_release(self, x, y, button, modifiers):
print('Released mouse at {}x{}'.format(x, y))
def on_mouse_press(self, x, y, button, modifiers):
if button == 1:
print('Pressed mouse at {}x{}'.format(x, y))
def on_mouse_drag(self, x, y, dx, dy, button, modifiers):
self.drag = True
print('Dragging mouse at {}x{}'.format(x, y))
def on_key_release(self, symbol, modifiers):
try:
del self.keys[symbol]
except:
pass
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE: # [ESC]
self.alive = 0
self.keys[symbol] = True
def pre_render(self):
pass
def render(self):
self.clear()
# FPS stuff (if you want to)
self.fps_count += 1
if time() - self.last_update > 1: # 1 sec passed
self.sprites['fps_label'].text = str(self.fps_count)
self.fps_count = 0
self.last_update = time()
#self.bg.draw()
self.pre_render()
for sprite in self.sprites:
self.sprites[sprite].draw()
self.flip()
def run(self):
while self.alive == 1:
self.render()
# -----------> This is key <----------
# This is what replaces pyglet.app.run()
# but is required for the GUI to not freeze
#
event = self.dispatch_events()
if __name__ == '__main__':
x = main()
x.run()
This way, you can actually interact with your class as if it were the pyglet class. For instance, you got on_key_press without having to use decorators etc.
You should make more functions for each thing you are doing. For example if you want to make a line you might have
import pyglet, os
class runGame():
widthDisplay = 1024
heightDiplay = 576
title = "Pokémon Life and Death: Esploratori del proprio Destino"
wra = pyglet.image.load("wra.png")
wrb = pyglet.image.load("wrb.png")
def __init__(self):
platform = pyglet.window.get_platform()
display = platform.get_default_display()
screen = display.get_default_screen()
self.widthScreen = screen.width
self.heightScreen = screen.height
self.xDisplay = int(self.widthScreen / 2 - self.widthDisplay / 2)
self.yDisplay = int(self.heightScreen / 2 - self.heightDiplay / 2)
self.Display = pyglet.window.Window(width=self.widthDisplay, height=self.heightDiplay, caption=self.title, resizable=False)
self.Display.set_location(self.xDisplay, self.yDisplay)
pyglet.app.run()
def drawLine(x, y):
drawLine(x, y)
You will have to make the functions based on what you want to do, but if you aren't going to use the runGame class multiple times before you kill the program, you shouldn't use OOP programming and use Procedural Programming.
You can create a custom pyglet window, by inheriting from the pyglet.window.Window class. After that in your init method call the super classes init (this will call the the init inside pyglet.window.Window class )Then overwrite the inherited methods (on_draw, on_key_press, on_key_release etc.). After that create an update method, which will be called by the pyglet.clock.schedule_interval 60 times in a second.Lastly just call the pyglet.app.run() method.
import pyglet
class GameWindow(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def on_draw(self):
self.clear()
def on_mouse_press(self, x, y, button, modifiers):
pass
def on_mouse_release(self, x, y, button, modifiers):
pass
def on_mouse_motion(self, x, y, dx, dy):
pass
def update(self, dt):
pass
if __name__ == "__main__":
window = GameWindow(1280, 720, "My Window", resizable=False)
pyglet.clock.schedule_interval(window.update, 1/60.0)
pyglet.app.run()
Related
I'm trying to make a simple application with pyglet. My main problem so far is that I can't seem to blit an image with alpha - all of the transparent pixels are converted into black pixels. I'm not sure whether the problem is with the loading of the image or the blitting. Here is a very basic overview of how I'm trying to render the image:
import pyglet
import pyglet.clock
window = pyglet.window.Window()
window.config.alpha_size = 8
#fancy text
text = pyglet.resource.image("text.png")
#background image
bg = pyglet.resource.image("bg.png")
bg.blit(0, 0)
text.blit(100, 100)
pyglet.app.run()
Any help is appreciated. Thanks in advance.
You most likely just need to enable GL ALPHA blends.
from pyglet.gl import *
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
But first of all, your code is not able to run.
Mostly because you don't declare a window.event function to handle the on_draw where you normally render things.
Secondly, you never clear your window (which will cause a mess).
Here's a minimal working example of your code:
import pyglet
import pyglet.clock
window = pyglet.window.Window()
window.config.alpha_size = 8
#fancy text
text = pyglet.resource.image("text.png")
#background image
bg = pyglet.resource.image("bg.png")
#window.event
def on_draw():
window.clear()
bg.blit(0, 0)
text.blit(100, 100)
pyglet.app.run()
Now this generates this:
And here's a working example of how you use the GL_BLEND feature:
import pyglet
import pyglet.clock
from pyglet.gl import *
window = pyglet.window.Window()
window.config.alpha_size = 8
#fancy text
text = pyglet.resource.image("text.png")
#background image
bg = pyglet.resource.image("bg.png")
#window.event
def on_draw():
window.clear()
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
bg.blit(0, 0)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
text.blit(100, 100)
pyglet.app.run()
This yields a result like so:
However, this code will quickly become messy.
So there's two things you can do. You can first, put your images into sprite objects. Secondly, make this a bit more object oriented.
First, we'll use sprites.
self.fancy_background = pyglet.sprite.Sprite(pyglet.image.load('bg.png'))
self.fancy_background.draw() # not blit!
Sprites automatically uses transparency, which makes your life (and code) a lot easier.
Secondly, we'll put these into a batch.
Batches are made to bunch A LOT of sprites so you can call .draw() on the batch, and all sprites in that batch gets insta-rendered.
self.background = pyglet.graphics.Batch()
self.fancy_background = pyglet.sprite.Sprite(pyglet.image.load('bg.png'), batch=self.background)
self.background.draw() # background, not fancy_background! And also not blit!!
Last and most certainly not least.
We'll put this into a class so we can do cool stuff later on.
import pyglet
import pyglet.clock
from pyglet.gl import *
key = pyglet.window.key
class main(pyglet.window.Window):
def __init__ (self, width=800, height=600, fps=False, *args, **kwargs):
super(main, self).__init__(width, height, *args, **kwargs)
self.x, self.y = 0, 0
self.background = pyglet.graphics.Batch()
self.texts = pyglet.graphics.Batch()
self.fancy_background = pyglet.sprite.Sprite(pyglet.image.load('bg.png'), batch=self.background)
self.fancy_text = pyglet.sprite.Sprite(pyglet.image.load('text.png'), batch=self.texts)
self.mouse_x = 0
self.mouse_y = 0
self.alive = 1
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def on_mouse_motion(self, x, y, dx, dy):
self.mouse_x = x
self.mouse_y = y
def on_mouse_press(self, x, y, button, modifiers):
if button == 1: # Left click
pass
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE: # [ESC]
self.alive = 0
def render(self):
self.clear()
self.background.draw()
self.texts.draw()
self.flip()
def run(self):
while self.alive == 1:
self.render()
# -----------> This is key <----------
# This is what replaces pyglet.app.run()
# but is required for the GUI to not freeze
#
event = self.dispatch_events()
if __name__ == '__main__':
x = main()
x.run()
BAM.
This code will enable you to create custom functions and custom "player objects" later on for instance. Also you can do collision detection easier and the code just looks a lot more structured (I threw in a little bonus features such as keyboard and mouse events).
Note tho, that the position of the sprites will default to x=0, y=0 as shown in the last picture. You can set the position with x=100 either on the variable/handle or when creating the sprite.
I am trying to have a circle that, when clicked, moves somewhere else on the screen. However, when I click the circle, nothing happens.
#IMPORT STUFF
import pyglet as pg
from random import randint
mouse = pg.window.mouse
#VARS
window = pg.window.Window(width = 640, height = 480)
score = 0
circleImg = pg.image.load("circle.png")
circle = pg.sprite.Sprite(circleImg, randint(1, window.width), randint(1, window.height))
text = pg.text.Label("Click red!", font_name = "Times New Roman", font_size = 18, x = 260, y = 10)
#DETECT MOUSE PRESS ON CIRCLE
#window.event
def on_mouse_press(x, y, button, modifiers):
if x == circle.x and y == circle.y:
circle.x = randint(1, window.width)
circle.y = randint(1, window.height)
#window.event
def on_draw():
window.clear()
text.draw()
circle.draw()
pg.app.run()
import pyglet
from pyglet.gl import *
from random import randint
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
class Circle(pyglet.sprite.Sprite):
def __init__(self, radiance=5, x=0, y=0):
self.texture = pyglet.image.load('circle.png')
super(Circle, self).__init__(self.texture)
def click(self, x, y):
if x >= self.x and y >= self.y:
if x <= self.x + self.texture.width and y <= self.y + self.texture.height:
return self
mouse = pyglet.window.mouse
#VARS
window = pyglet.window.Window(width = 640, height = 480)
score = 0
#circleImg = pyglet.image.load("circle.png")
#circle = pyglet.sprite.Sprite(circleImg, randint(1, window.width), randint(1, window.height))
circle = Circle(x=50, y=50)
text = pyglet.text.Label("Click red!", font_name = "Times New Roman", font_size = 18, x = 260, y = 10)
#DETECT MOUSE PRESS ON CIRCLE
#window.event
def on_mouse_press(x, y, button, modifiers):
if circle.click(x, y):
print('Clicked in circle')
circle.x = randint(0, window.width - 10)
circle.y = randint(0, window.height - 10)
#window.event
def on_draw():
window.clear()
text.draw()
circle.draw()
pyglet.app.run()
A short description of what this does is it creates a custom class called Circle that inherits the Sprite class. It loads the circle.png as a texture with a alpha channel that gets blended by the GL library.
We add a custom function called click that checks if the lowest x,y coordinates are higher than the circles lowest x,y, then we check if the cursor is below x+width and same for y of the image region.
If that's the case, we return the circle sprite class as a True value in case we want to use the sprite.
Future enhancements:
You should draw the circle using gl functions, hence why I've defined radiance in the class definitions. However radiance here is never used, it's a placeholder for the future.
This is so you can use math to defined if you actually clicked within the circle, but this is beyond my scope of quick answers.. I would have to do a lot of debugging myself in order to get the math to add up (it's not my strong side).
What makes it work now is that we use the image width, height, x and y data to crudely check if we're within the image, aka "the circle".
trying to draw over sprite or change picture pyglet
As a bonus, I'll add this answer to the list of enhancements because it contains some stuff that might be useful. One would be to replace 90% of your code with a custom pyglet.window.Window class to replace global variables and decorators and stuff.
And it would look something like this:
import pyglet
from pyglet.gl import *
from random import randint
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
key = pyglet.window.key
class Circle(pyglet.sprite.Sprite):
def __init__(self, radiance=5, x=0, y=0):
self.texture = pyglet.image.load('circle.png')
super(Circle, self).__init__(self.texture)
def click(self, x, y):
if x >= self.x and y >= self.y:
if x <= self.x + self.texture.width and y <= self.y + self.texture.height:
return self
class MainScreen(pyglet.window.Window):
def __init__ (self):
super(MainScreen, self).__init__(800, 600, fullscreen = False)
self.x, self.y = 0, 0
self.bg = pyglet.sprite.Sprite(pyglet.image.load('background.jpg'))
self.sprites = {}
self.sprites['circle'] = Circle(x=50, y=50)
self.sprites['label'] = pyglet.text.Label("Click red!", font_name = "Times New Roman", font_size = 18, x = 260, y = 10)
self.alive = 1
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def on_mouse_press(self, x, y, button, modifiers):
if self.sprites['circle'].click(x, y):
print('Clicked in circle')
self.sprites['circle'].x = randint(0, self.width - 10)
self.sprites['circle'].y = randint(0, self.height - 10)
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE: # [ESC]
self.alive = 0
def render(self):
self.clear()
self.bg.draw()
for sprite_name, sprite_obj in self.sprites.items():
sprite_obj.draw()
self.flip()
def run(self):
while self.alive == 1:
self.render()
# -----------> This is key <----------
# This is what replaces pyglet.app.run()
# but is required for the GUI to not freeze
#
event = self.dispatch_events()
x = MainScreen()
x.run()
I'm not familiar with pyglet, but I'm guessing the problem is that you're checking whether x == circle.x etc, which means it only moves when you click the single pixel at the exact centre of the circle. Try some kind of maximum distance from the centre (e.g. a hypotenuse math.sqrt( (x-circle.x)**2 + (y-circle.y)**2) < circle.radius
I am trying to create a simple program in Pyglet that shows an animation and retrieves some mouse input and saves it to a text file. The code I have shows a significant unstable frame rate even when I am not using the mouse.
I have also looked at similar questions and the answers suggest to use a subclassed window, or to call the function on_draw with schedule_interval. I do not know, however, how to use a subclassed window to display my animation and, when I try to call on_draw with schedule_interval I get the error that on_draw does not receives any argument.
This is part of the code I am using:
fps = pyglet.clock.ClockDisplay()# Show FPS
#mywindow.event
def on_mouse_press(x, y, button, modifiers):
global timeStart, file, count
timeNow = time.clock() - timeStart
if button == mouse.LEFT:
print('left click press in {}').format(timeNow)
with open(out_file_name, 'a') as file:
file.write(str(count) +'\t'+ str(timeNow) +'\t'+ '-1\n')
#file.write('' + count + timeNow + 'left click press\n')
count += 1
def update_frames(dt):
global x
x=x+1
#mywindow.event
def on_draw():
pyglet.gl.glClearColor(0,0,0,0)
mywindow.clear()
glColor4f(1,0,0,1)
drawSquare(x,y)#this draws an opengl square
fps.draw()# Show FPS
dt = 1/10.0
pyglet.clock.schedule_interval(update_frames,dt)
pyglet.app.run()
What can I add to the code in order to obtain an stable frame rate?
I'd use something like this instead:
import pyglet
from pyglet.gl import *
from collections import OrderedDict
from time import time
from os.path import abspath
class GUI(pyglet.window.Window):
def __init__(self):
super(GUI, self).__init__(640,340, caption='Test')
pyglet.gl.glClearColor(1, 1, 1, 1)
self.alive = True
self.batches = OrderedDict()
self.batches['apples'] = pyglet.graphics.Batch()
self.framerate = 0, time()
self.count = 0
def render(self, *args):
self.clear()
#glColor4f(1,0,0,1)
#drawSquare(x,y)
if time() - self.framerate[1] > 1:
print('fps:',self.framerate[0])
self.framerate = 0, time()
else:
# Not an optimal way to do it, but it will work.
self.framerate = self.framerate[0]+1, self.framerate[1]
self.flip()
def on_draw(self):
self.render()
def on_close(self):
self.alive = False
def on_key_press(self, symbol, modkey):
pass
def on_key_release(self, symbol, modkey):
pass
def on_mouse_release(self, x, y, button, modifiers):
pass
def on_mouse_press(self, x, y, button, modifiers):
self.count += 1
with open('debug.log', 'w') as fh:
fh.write(str(count))
def on_mouse_motion(self, x, y, dx, dy):
pass
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
pass
def run(self):
while self.alive:
event = self.dispatch_events()
if event:
print(event)
self.render()
if __name__ == '__main__':
x = GUI()
pyglet.clock.set_fps_limit(60)
x.run()
For one, this code actually produces 60 FPS,
You get way better control over your application and your main loop.
Secondly, the coding style is perhaps a personal preference but throwing stuff into class objects rather than doing a huge list of functions which you attach to say #window.update etc is more to my liking.. The code looks cleaner.
Give it a go, see if it works.
Note: Key here is event = self.dispatch_events() which must be called for each iteration, it's what replaces app.run().
Tie this together with objects and rendering them
class House(pyglet.sprite.Sprite):
def __init__(self):
self.texture = pyglet.image.load(abspath('./image.png'))
super(House, self).__init__(self.texture)
self.x = 0
self.y = 0
self.rotation = 0
self.name = 'house'
self.anchor = 'center'
def swap_image(self, image):
self.texture = pyglet.image.load(abspath(image))
self.image = self.texture
def rotate(self, deg):
self.image.anchor_x = self.image.width / 2
self.image.anchor_y = self.image.height / 2
self.rotation = self.rotation+deg
if self.anchor != 'center':
self.image.anchor_x = 0
self.image.anchor_y = 0
return True
def click(self):
print('Clicked:',self.name)
def work(self, *args):
pass
def click_check(self, x, y):
if x > self.x and x < (self.x + self.width):
if y > self.y and y < (self.y + self.height):
return self
def move(self, x, y):
if self.moveable:
self.x += x
self.y += y
def _draw(self):
self.draw()
in GUI() you'll do:
class GUI(pyglet.window.Window):
def __init__(self):
super(GUI, self).__init__(640,340, caption='Test')
...
self.house = House()
def render(self, *args):
self.house.rotate(1)
self.house._draw()
This should create a "house" (or whatever) and rotate the picture 1 degrees for each render occations, meaning you'll be rotating it 60 degrees a second with a nice flow.
There's more stuff to this than just this, but it's a simplification of what i usually use to squeeze out FPS while still maintaining readable code.. Because graphics get messy quite quickly.
This code displays the image assassin1.png on a black screen standing still at position (50, 80).
The goal is to induce the pymunk gravity on that image so that it falls down. I followed the pymunk tutorial which is written using pygame and tried to adapt that. I don't know why my code isn't applying gravity to the my image. Could someone tell me what I am doing wrong and what I should change to make it work properly?
import pyglet
import pymunk
class PymunkSpace(object):
def assassin_space(self, space):
self.space = space
self.mass = 91
self.radius = 14
self.inertia = pymunk.moment_for_circle(self.mass, 0, self.radius)
self.body = pymunk.Body(self.mass, self.inertia)
self.body.position = 50, 80
self.shape = pymunk.Circle(self.body, self.radius)
self.space.add(self.body, self.shape)
return self.shape
class Assassin(pyglet.sprite.Sprite):
def __init__(self, batch, img, x, y):
pyglet.sprite.Sprite.__init__(self, img, x , y )
class Game(pyglet.window.Window):
def __init__(self):
pyglet.window.Window.__init__(self, width = 315, height = 220)
self.batch_draw = pyglet.graphics.Batch()
self.a_space = PymunkSpace().assassin_space(space)
self.player1 = Assassin(batch = self.batch_draw, img = pyglet.image.load("assassin1.png"), x = self.a_space.body.position.x ,y = self.a_space.body.position.y )
def on_draw(self):
self.clear()
self.batch_draw.draw()
self.player1.draw()
space.step(1/50.0)
if __name__ == "__main__":
space = pymunk.Space()
space.gravity = (0.0, -900.)
window = Game()
pyglet.app.run()
The problem is that you set the location of your Sprite once:
self.player1 = Assassin(batch = self.batch_draw, img = pyglet.image.load("assassin1.png"), x = self.a_space.body.position.x ,y = self.a_space.body.position.y )
class Assassin(pyglet.sprite.Sprite):
def __init__(self, batch, img, x, y):
pyglet.sprite.Sprite.__init__(self, img, x , y )
but this location never gets updated.
Another problem is that in the pygame example, space.step(1/50.0) is called every iteration of the main loop, while your's only gets called when the window is drawn.
So, first, you should ensure space.step gets called every frame. Do so by using a clock:
class Game(pyglet.window.Window):
def __init__(self):
...
pyglet.clock.schedule(self.update)
def on_draw(self):
self.clear()
self.batch_draw.draw()
self.player1.draw()
def update(self, dt):
space.step(dt)
The next step is ensuring the location of the sprite is keeped in sync with the pyglet object.
Change your Assassin class:
class Assassin(pyglet.sprite.Sprite):
def __init__(self, batch, img, space):
self.space = space
pyglet.sprite.Sprite.__init__(self, img, self.space.body.position.x , self.space.body.position.y)
def update(self):
self.x = self.space.body.position.x
self.y = self.space.body.position.y
Create your Assassin instance like this:
class Game(pyglet.window.Window):
def __init__(self):
pyglet.window.Window.__init__(self, width = 315, height = 220)
self.batch_draw = pyglet.graphics.Batch()
self.a_space = PymunkSpace().assassin_space(space)
self.player1 = Assassin(batch = self.batch_draw, img = pyglet.image.load("assassin1.png"), space = self.a_space)
pyglet.clock.schedule(self.update)
and call self.player1.update() in your new update method:
class Game(pyglet.window.Window):
def __init__(self):
...
def on_draw(self):
...
def update(self, dt):
self.player1.update()
space.step(dt)
(And you should probably get rid of some unneeded instance members, but that's another topic)
I'm new to working with Pyglet and I've written a small program which moves a ball around the screen. Right now I'm having difficulty establishing a steady frame rate of 60 fps. While Pyglet is supposed to sync with my monitor's refresh rate of 60Hz, Pyglet is setting my fps to half of my refresh rate (ex. when 60Hz, 30 fps). Is there something wrong in my code that is causing this?
import pyglet
import physicalobject
import random
from pyglet.window import mouse
pyglet.resource.path = ['./resources']
pyglet.resource.reindex()
ball_image = pyglet.resource.image("ball2.png")
#sets clock format
fps_display = pyglet.clock.ClockDisplay(format='%(fps).2f fps')
def center_image(image):
image.anchor_x = image.width/2
image.anchor_y = image.height/2
center_image(ball_image)
ball = physicalobject.PhysicalObject(img=ball_image, x = 400, y = 300)
ball.scale = .2
ball.velocity_x = random.randint(-4,4)*150
ball.velocity_y = random.randint(-4,4)*150
#Calls update function to set new ball position based on velocity
def update(dt):
ball.update(dt)
#window.event
def on_mouse_drag(x, y, dx, dy, button, modifiers):
ball.x = x
ball.y = y
ball.velocity_x = dx * 20
ball.velocity_y = dy * 20
#window.event
def on_draw():
window.clear()
ball.draw()
fps_display.draw()
def main():
pyglet.clock.schedule_interval(update, 1/120.0)
pyglet.app.run()
if __name__ == '__main__':
main()
Pyglet simply doesn't handle it correctly on some systems, you have to disable your application window's vsync in order to get it to work. Here's an example script you can run to get a feel for how it works:
import pyglet
# Show FPS
fps = pyglet.clock.ClockDisplay()
# The game window
class Window(pyglet.window.Window):
def __init__(self):
super(Window, self).__init__(vsync = False)
# Run "self.update" 128 frames a second and set FPS limit to 128.
pyglet.clock.schedule_interval(self.update, 1.0/128.0)
pyglet.clock.set_fps_limit(128)
# You need the dt argument there to prevent errors,
# it does nothing as far as I know.
def update(self, dt):
pass
def on_draw(self):
pyglet.clock.tick() # Make sure you tick the clock!
self.clear()
fps.draw()
# Create a window and run
win = Window()
pyglet.app.run()
import pyglet
from time import time, sleep
class Window(pyglet.window.Window):
def __init__(self, refreshrate):
super(Window, self).__init__(vsync = False)
self.frames = 0
self.framerate = pyglet.text.Label(text='Unknown', font_name='Verdana', font_size=8, x=10, y=10, color=(255,255,255,255))
self.last = time()
self.alive = 1
self.refreshrate = refreshrate
def on_draw(self):
self.render()
def render(self):
self.clear()
if time() - self.last >= 1:
self.framerate.text = str(self.frames)
self.frames = 0
self.last = time()
else:
self.frames += 1
self.framerate.draw()
self.flip()
def on_close(self):
self.alive = 0
def run(self):
while self.alive:
self.render()
event = self.dispatch_events()
sleep(1.0/self.refreshrate)
win = Window(23) # set the fps
win.run()
Note the lack of the clock feature.
Also, try setting vsync = True and removing the sleep(1.0/self.refreshrate), this will lock the refresh rate to your monitor.
Also, note that i don't use pyglet.app.run() to lock the rendering process, i call self.dispatch_events() instead.. it doesn't really do anything except let the graphic "poll" and move on, without it.. pyglet waits for a poll to occur, which pyglet.app.run() normally does.