from ursina import *
#preloads a cube
class Voxel(Button):
def __init__(self):
super().__init__(self, position = (0,0,0))(
parent = scene,
position = position,
model = 'cube',
origin_y = 0.5,
texture = 'white_cube',
color = color.white,
highlight_color = color.lime)
app = Ursina()
#loads a cube
for z in range(8):
for x in range(8):
Voxel = Voxel(position = (x,0,z))
app.run()
the error is here please help me:
File "D:\project\game.py", line 18, in <module>
Voxel = Voxel(position=(x,0,z)) TypeError: Voxel.__init__() got an unexpected keyword argument 'position'
so what I'm trying to do with this code is make cubes
You likely copy-pasted to the wrong place.
For example, this part of your super call (self, position = (0,0,0)), was probably intended for your class __init__ method.
def __init__(self, position = (0,0,0)):
Moving that makes your class functional.
class Voxel(Button):
def __init__(self, position = (0,0,0)):
super().__init__(
parent = scene,
position = position,
model = 'cube',
origin_y = 0.5,
texture = 'white_cube',
color = color.white,
highlight_color = color.lime)
You also need to change the name of your class instance at Voxel = Voxel(position = (x,0,z)) from Voxel to something else. As it stands, anything after the first loop would refer to an instance of Voxel and not the class itself.
Full working code:
from ursina import *
#preloads a cube
class Voxel(Button):
def __init__(self, position):
super().__init__(
parent = scene,
position = position,
model = 'cube',
origin_y = 0.5,
texture = 'white_cube',
color = color.white,
highlight_color = color.lime)
app = Ursina()
#loads a cube
for z in range(8):
for x in range(8):
voxel = Voxel(position = (x,0,z))
app.run()
Related
I'm trying to run my program:
from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
app = Ursina()
window.fullscreen = True
class Voxel(Button):
def __init__(self, colour, position = (0, 0, 0)):
super().__init__(
parent = scene,
position = position,
model = "cube",
orgin_y = 0.5,
texture = "white_cube",
color = colour,
)
def start_game(self):
self.colour = color.white
def input(self, key):
if self.hovered:
if key == "right mouse up":
voxel = Voxel(position = self.position + mouse.normal, colour = self.colour)
if key == "left mouse up":
destroy(self)
if key == "0":
self.colour = color.white
if key == "1":
self.colour = color.lime
for z in range(22):
for x in range(22):
voxel = Voxel(position = (x, 0, z), colour = color.lime)
voxel.start_game()
player = FirstPersonController()
app.run()
I'm using python 3.10.6 and Idle.
When I run the program it works as expected except when I choose green after I place a block it turn into white. If I spam click I get the error:
File "C:\Users\game.py", line 24, in input
voxel = Voxel(position = self.position + mouse.normal, colour = self.colour)
AttributeError: 'Voxel' object has no attribute 'colour'
This code appears to be using both color and colour in multiple places.
It looks like the ursina library uses the color form.
I would suggest using color everywhere in your code to stay consistent with the library you are using. It will be harder to maintain if you need to translate between spellings and remember which version is used in which place.
Additionally, even though their examples may use from ursina import *, it is not the best practice to do so because it makes it unclear what names are available in the namespace. It would be better to explicitly do from ursina import Ursina, Button, window.
You are using colour instead of color when using self.colour and also when calling Voxel.
You should do:
voxel = Voxel(position = self.position + mouse.normal, colour = self.color)
And:
self.color = color
The solution is to replace colour with color in your code.
I am trying to make minecraft in ursina but whenever I run it, it says:
TypeError: Voxel.__init__() got an unexpected keyword argument 'position'
This is my code
from ursina import *
from ursina.prefabs.first_person_controller import FirstPersonController
app = Ursina()
player = FirstPersonController()
Sky()
block = load_model('block.obj')
grass_texture = load_texture('grass_block.png')
class Voxel(Button):
def __init__(self, positon = (0,0,0)):
super().__init__(
parent = scene,
position = position,
model = block,
origin_y = 0.5,
texture = grass_texture,
color = color.color(0,0,random.uniform(0.9, 1)),
highlight_color = color.lime)
def input(self, key):
if self.hovered:
if key == 'left mouse down':
voxel = Voxel(position = self.position + mouse.normal)
if key == 'right mouse down':
destroy(self)
for z in range(20):
for x in range(20):
voxel = Voxel(position = (x,0,z))
app.run()
There's a typo in Voxel's initializer declaration:
def __init__(self, positon = (0,0,0)):
You have positon (instead of position).
Correct that, and you should be fine:
def __init__(self, position=(0, 0, 0)):
Right now I am creating a maze path finding algorithm using breadth first search. The algorithm to find the 'best path' seems to work. The problem however is that I am not sure how to make the sprite (turtle) move through that best path.
Here is code:
import turtle
import time
import sys
from collections import deque
bs = turtle.Screen()
bs.bgcolor("black")
bs.setup(1300,700)
class Building(turtle.Turtle): # Define building class
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square") # Shape of the building
self.color("grey") # Colour of the building
self.penup() # Lift the pen up so it does not leave a trail
self.speed('fast') # Sets the speed that the building is drawn on the screen
class Road(turtle.Turtle): # Define road class
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square") # Shape of the road
self.color("white") # Colour of the road
self.penup() # Lift the pen up so it does not leave a trail
self.hideturtle()
self.speed('fast') # Sets the speed that the road is drawn on the screen
class Start(turtle.Turtle): # Define start class
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square") # Shape of the start point
self.color('green') # Colour of the start point
self.penup() # Lift the pen up so it does not leave a trail
self.hideturtle()
self.speed('fast')
class Route(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square")
self.color("yellow")
self.penup()
self.hideturtle()
self.speed('fast')
class End(turtle.Turtle): # Define end class
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square") # Shape of the end point
self.color("red") # Colour of the end point
self.penup() # Lift the pen up so it does not leave a trail
self.hideturtle()
self.speed('fast')
class Searcher(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square")
self.color("white")
self.penup()
self.hideturtle()
self.speed('fast')
class sprite(turtle.Turtle): # Define sprite class
noOfSteps = 0 # Declare variable noOfSteps and instantiate it as 0
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("turtle") # Shape of the sprite
self.color("purple") # Colour of the sprite
self.penup() # Lift the pen up so it does not leave a trail
self.hideturtle()
self.speed('fast')
def moveSprite(self):
start.color('green')
start.stamp()
searcher.color('red')
searcher.stamp()
self.goto(start_x, start_y)
self.showturtle()
# self.goto(solution[x,y])
# Read maze txt file
def readMaze(mazeSet, filename):
mazeFile = open(filename, "r")
lines = mazeFile.readlines()
for line in lines:
line = line.strip()
row = [c for c in line]
mazeSet.append(row)
mazeSet = [] # This declares the maze as an empty list
readMaze(mazeSet, "CA1_Map.txt") # This reads the maze into the list
# Setting up of maze
def setupMaze(mazeSet):
global start_x, start_y, end_x, end_y
m_height, m_width = len(mazeSet), len(mazeSet[0]) # Define maze height and maze width
for y in range(m_height): # Select each line in the maze
for x in range(m_width): # Identify each character in the line
character = mazeSet[y][x] # Assign the maze reference to the variable 'character'
screen_x = ((x - m_width) * 24) + 150 # Assign screen_x to screen starting position for x coords
screen_y = ((m_width - y) * 24) - 200 # Assign screen_y to screen starting position for y coords
if character == "X":
building.goto(screen_x, screen_y)
building.stamp()
walls.append((screen_x, screen_y))
if character == "." or character == 'e':
path.append((screen_x, screen_y))
if character == "e":
end_x, end_y = screen_x, screen_y
searcher.color('red')
searcher.goto(screen_x, screen_y)
searcher.stamp()
searcher.color('white')
finish.append((screen_x, screen_y))
if character == "s":
start_x, start_y = screen_x, screen_y
start.goto(screen_x,screen_y)
start.stamp()
def search(x,y):
frontier.append((x, y))
solution[x,y] = x,y
while len(frontier) > 0:
time.sleep(0)
x, y = frontier.popleft()
if(x - 24, y) in path and (x - 24, y) not in visited:
cell = (x - 24, y)
solution[cell] = x, y
frontier.append(cell)
visited.add((x-24, y))
if (x, y - 24) in path and (x, y - 24) not in visited:
cell = (x, y - 24)
solution[cell] = x, y
frontier.append(cell)
visited.add((x, y - 24))
if(x + 24, y) in path and (x + 24, y) not in visited:
cell = (x + 24, y)
solution[cell] = x, y
frontier.append(cell)
visited.add((x + 24, y))
if(x, y + 24) in path and (x, y + 24) not in visited:
cell = (x, y + 24)
solution[cell] = x, y
frontier.append(cell)
visited.add((x, y + 24))
searcher.goto(x,y)
searcher.stamp()
def correctRoute(x, y):
route.goto(x, y)
route.stamp()
while (x, y) != (start_x, start_y):
route.goto(solution[x, y])
route.stamp()
x, y = solution[x, y]
def endProgram():
bs.exitonclick()
sys.exit()
# Main program
# Setting up classes
building = Building()
road = Road()
start = Start()
end = End()
searcher = Searcher()
route = Route()
sprite = sprite()
# Setting up lists
walls = []
path = []
finish = []
visited = set()
frontier = deque()
solution = {}
setupMaze(mazeSet)
search(start_x, start_y)
correctRoute(end_x, end_y)
while True:
sprite.moveSprite()
The image of the maze currently looks like this:
So what I need to do is make the purple turtle (kind of hard to see) move from the green square to red square through the best path (yellow squares).
Step 1: At the function where the program determines the correct route,
record each coordinate into a list,
and return the list (inverted) so it can be accessed outside the function:
def correctRoute(x, y):
routes = [(x, y)]
route.goto(x, y)
route.stamp()
while (x, y) != (start_x, start_y):
route.goto(solution[x, y])
route.stamp()
x, y = solution[x, y]
routes.append((x, y))
return routes[::-1]
Step 2: Give the moveSprite function another parameter, and the parameter will be the list of coordinates.
the list will then be split into two parts: the starting coordinates and the path. Before calling self.showturtle(),
make sure that the turtle is in its proper starting position first.
Using a for loop, loop through the path list with time.sleep and make the turtle go to each of the coordinates:
def moveSprite(self, routes):
starting, path = routes[0], routes[1:]
start.color('green')
start.stamp()
searcher.color('red')
searcher.stamp()
self.goto(starting)
self.showturtle()
for path in path:
time.sleep(0.3)
self.goto(path)
Step 3: At the very bottom of your code, assign the correctRoute call to a variable to retrive the coordinates.
Remove the while loop, and put the list of coordinates into the moveSprite function:
routes = correctRoute(end_x, end_y)
sprite.moveSprite(routes)
All together:
import turtle
import time
import sys
from collections import deque
bs = turtle.Screen()
bs.bgcolor("black")
bs.setup(1300,700)
class Building(turtle.Turtle): # Define building class
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square") # Shape of the building
self.color("grey") # Colour of the building
self.penup() # Lift the pen up so it does not leave a trail
self.speed('fast') # Sets the speed that the building is drawn on the screen
class Road(turtle.Turtle): # Define road class
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square") # Shape of the road
self.color("white") # Colour of the road
self.penup() # Lift the pen up so it does not leave a trail
self.hideturtle()
self.speed('fast') # Sets the speed that the road is drawn on the screen
class Start(turtle.Turtle): # Define start class
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square") # Shape of the start point
self.color('green') # Colour of the start point
self.penup() # Lift the pen up so it does not leave a trail
self.hideturtle()
self.speed('fast')
class Route(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square")
self.color("yellow")
self.penup()
self.hideturtle()
self.speed('fast')
class End(turtle.Turtle): # Define end class
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square") # Shape of the end point
self.color("red") # Colour of the end point
self.penup() # Lift the pen up so it does not leave a trail
self.hideturtle()
self.speed('fast')
class Searcher(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square")
self.color("white")
self.penup()
self.hideturtle()
self.speed('fast')
class sprite(turtle.Turtle): # Define sprite class
noOfSteps = 0 # Declare variable noOfSteps and instantiate it as 0
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("turtle") # Shape of the sprite
self.color("purple") # Colour of the sprite
self.penup() # Lift the pen up so it does not leave a trail
self.hideturtle()
self.speed('fast')
def moveSprite(self, routes):
starting, path = routes[0], routes[1:]
start.color('green')
start.stamp()
searcher.color('red')
searcher.stamp()
self.goto(starting)
self.showturtle()
for path in path:
time.sleep(0.3)
self.goto(path)
# Read maze txt file
def readMaze(mazeSet, filename):
mazeFile = open(filename, "r")
lines = mazeFile.readlines()
for line in lines:
line = line.strip()
row = [c for c in line]
mazeSet.append(row)
mazeSet = [] # This declares the maze as an empty list
readMaze(mazeSet, "CA1_Map.txt") # This reads the maze into the list
# Setting up of maze
def setupMaze(mazeSet):
global start_x, start_y, end_x, end_y
m_height, m_width = len(mazeSet), len(mazeSet[0]) # Define maze height and maze width
for y in range(m_height): # Select each line in the maze
for x in range(m_width): # Identify each character in the line
character = mazeSet[y][x] # Assign the maze reference to the variable 'character'
screen_x = ((x - m_width) * 24) + 150 # Assign screen_x to screen starting position for x coords
screen_y = ((m_width - y) * 24) - 200 # Assign screen_y to screen starting position for y coords
if character == "X":
building.goto(screen_x, screen_y)
building.stamp()
walls.append((screen_x, screen_y))
if character == "." or character == 'e':
path.append((screen_x, screen_y))
if character == "e":
end_x, end_y = screen_x, screen_y
searcher.color('red')
searcher.goto(screen_x, screen_y)
searcher.stamp()
searcher.color('white')
finish.append((screen_x, screen_y))
if character == "s":
start_x, start_y = screen_x, screen_y
start.goto(screen_x,screen_y)
start.stamp()
def search(x,y):
frontier.append((x, y))
solution[x,y] = x,y
while len(frontier) > 0:
time.sleep(0)
x, y = frontier.popleft()
if(x - 24, y) in path and (x - 24, y) not in visited:
cell = (x - 24, y)
solution[cell] = x, y
frontier.append(cell)
visited.add((x-24, y))
if (x, y - 24) in path and (x, y - 24) not in visited:
cell = (x, y - 24)
solution[cell] = x, y
frontier.append(cell)
visited.add((x, y - 24))
if(x + 24, y) in path and (x + 24, y) not in visited:
cell = (x + 24, y)
solution[cell] = x, y
frontier.append(cell)
visited.add((x + 24, y))
if(x, y + 24) in path and (x, y + 24) not in visited:
cell = (x, y + 24)
solution[cell] = x, y
frontier.append(cell)
visited.add((x, y + 24))
searcher.goto(x,y)
searcher.stamp()
def correctRoute(x, y):
routes = [(x, y)]
route.goto(x, y)
route.stamp()
while (x, y) != (start_x, start_y):
route.goto(solution[x, y])
route.stamp()
x, y = solution[x, y]
routes.append((x, y))
return routes[::-1]
def endProgram():
bs.exitonclick()
sys.exit()
# Main program
# Setting up classes
building = Building()
road = Road()
start = Start()
end = End()
searcher = Searcher()
route = Route()
sprite = sprite()
# Setting up lists
walls = []
path = []
finish = []
visited = set()
frontier = deque()
solution = {}
setupMaze(mazeSet)
search(start_x, start_y)
routes = correctRoute(end_x, end_y)
sprite.moveSprite(routes)
If you want the turtle to change its direction at each turn, use this as the moveSprite function:
def moveSprite(self, routes):
starting, routes = routes[0], routes[1:]
start.color('green')
start.stamp()
searcher.color('red')
searcher.stamp()
self.goto(starting)
self.showturtle()
for path1, path2 in zip(routes, routes[1:]):
self.goto(path1)
time.sleep(0.3)
if path1[0] == path2[0]: # If the x coordinates of two consecutive moves are equal, that means that the turtle is moving along the `y` axis
if path1[1] > path2[1]:
self.setheading(270)
else:
self.setheading(90)
else: # If the x coordinates of two consecutive moves aren't equal, that means that the turtle is moving along the `x` axis
if path1[0] > path2[0]:
self.setheading(180)
else:
self.setheading(0)
self.goto(path2)
I am using VTK in my project, and I meet a problem about the coordinate convertion: from display coordinate vs world coordiante.
First, I show a cone and set the window size to (500, 500). Then, I calcualte the world point using the (250, 250) display point. The display point (250, 250) is located in the cone.
picker = vtk.vtkPropPicker()
picker.Pick(250, 250, 0, self.ren)
if picker.GetActor():
coordinate = vtk.vtkCoordinate()
coordinate.SetCoordinateSystemToDisplay()
coordinate.SetValue(250, 250, 0)
position = coordinate.GetComputedWorldValue(self.ren)
self.position = position
I show this point as a red point.
Then, I rotate the screen, and I want to convert the world point as the display point. In my thought, the red point would move along with the cone.
coordinate = vtk.vtkCoordinate()
coordinate.SetCoordinateSystemToWorld()
point = self.position
coordinate.SetValue(point[0], point[1], point[2])
displayCoor = coordinate.GetComputedDisplayValue(self.ren)
However, the red point is seperated from the cone. Is there something wrong with the coordinate convertion?
The whole code is:
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys, os
import numpy as np
import vtk, qimage2ndarray
class vtkLabel(QLabel):
def __init__(self):
super(vtkLabel, self).__init__()
self.setFixedSize(500, 500)
cone = vtk.vtkConeSource()
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(cone.GetOutputPort())
actor = vtk.vtkActor()
actor.SetMapper(mapper)
ren = vtk.vtkRenderer()
ren.AddActor(actor)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
renWin.SetOffScreenRendering(1)
imageFilter = vtk.vtkWindowToImageFilter()
imageFilter.SetInput(renWin)
self.ren = ren
self.renWin = renWin
self.imageFilter = imageFilter
def mousePressEvent(self, QMouseEvent):
super().mousePressEvent(QMouseEvent)
pos = QMouseEvent.pos()
x = pos.x()
y = pos.y()
self.lastPos = [x, y]
def mouseReleaseEvent(self, QMouseEvent):
super().mouseReleaseEvent(QMouseEvent)
self.lastPos = None
def mouseMoveEvent(self, QMouseEvent):
super().mouseMoveEvent(QMouseEvent)
pos = QMouseEvent.pos()
x = pos.x()
y = pos.y()
if self.lastPos != None:
if QMouseEvent.buttons() == Qt.RightButton:
dy = self.lastPos[1] - y
center = self.ren.GetCenter()
dyf = dy/center[1]
import math
val = math.pow(1.1, dyf)
self.ren.GetActiveCamera().Dolly(val)
if QMouseEvent.buttons() == Qt.LeftButton:
dx = x - self.lastPos[0]
dy = self.lastPos[1] - y
size = self.renWin.GetSize()
delta_elevation = -20.0 / size[1]
delta_azimuth = -20.0 / size[0]
rxf = dx * delta_azimuth
ryf = dy * delta_elevation
camera = self.ren.GetActiveCamera()
camera.Azimuth(rxf)
camera.Elevation(ryf)
camera.OrthogonalizeViewUp()
self.ren.ResetCameraClippingRange()
self.ren.UpdateLightsGeometryToFollowCamera()
self.ren.Render()
self.calculationForDisplay()
def resizeEvent(self, QMouseEvent):
super().resizeEvent(QMouseEvent)
self.renWin.SetSize(self.width(), self.height())
self.calculationForDisplay()
picker = vtk.vtkPropPicker()
picker.Pick(250, 250, 0, self.ren)
if picker.GetActor():
coordinate = vtk.vtkCoordinate()
coordinate.SetCoordinateSystemToDisplay()
coordinate.SetValue(250, 250, 0)
position = coordinate.GetComputedWorldValue(self.ren)
self.position = position
print('the point is one of the cone point')
else:
raise RuntimeError('the point is not one of the cone point')
def calculationForDisplay(self):
self.renWin.Render()
self.imageFilter.Modified()
self.imageFilter.Update()
displayImg = self.imageFilter.GetOutput()
dims = displayImg.GetDimensions()
from vtk.util.numpy_support import vtk_to_numpy
numImg = vtk_to_numpy(displayImg.GetPointData().GetScalars())
numImg = numImg.reshape(dims[1], dims[0], 3)
numImg = numImg.transpose(0, 1, 2)
numImg = np.flipud(numImg)
displayQImg = qimage2ndarray.array2qimage(numImg)
pixmap = QPixmap.fromImage(displayQImg)
self.pixmap = pixmap
self.update()
def paintEvent(self, QPaintEvent):
super(vtkLabel, self).paintEvent(QPaintEvent)
painter = QPainter(self)
width = self.width()
height = self.height()
painter.drawPixmap(QPoint(0, 0), self.pixmap, QRect(0, 0, width, height))
coordinate = vtk.vtkCoordinate()
coordinate.SetCoordinateSystemToWorld()
point = self.position
coordinate.SetValue(point[0], point[1], point[2])
displayCoor = coordinate.GetComputedDisplayValue(self.ren)
x = displayCoor[0]
y = displayCoor[1]
y = self.height() - y
painter.setPen(QPen(QColor(255, 0, 0), 5))
painter.drawPoint(x, y)
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setFixedSize(500, 500)
self.imageLabel = vtkLabel()
self.setCentralWidget(self.imageLabel)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
Update:
Finally, I know what's wrong with my code.
In the resizeEvent, I obtain the world point by:
coordinate = vtk.vtkCoordinate()
coordinate.SetCoordinateSystemToDisplay()
coordinate.SetValue(250, 250, 0)
position = coordinate.GetComputedWorldValue(self.ren)
Actually, the z should not be 0. We should use the following code to obtain the point:
picker = vtk.vtkPropPicker()
picker.Pick(250, 250, 0, self.ren)
pos = picker.GetPickPosition()
Then, everything is OK.
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)