cant properly make the player move on mobile joystick project [duplicate] - python

This question already has answers here:
how to make sprite move upwards and downwards with joystick in pygame
(1 answer)
How do I get xbox controls outside event loop in pygame?
(1 answer)
problems with pygame controller support
(1 answer)
Closed 2 days ago.
Trying to make mobile joystick, went well until i stumbled on a roadblock, that is trying to make a player move.
the problem is, the player position isn't really moving, its only set on the position of the given x,y mouse pos, thus giving the player position on the center.
from pygame import *;
import pygame;
import math;
import os;
pygame.init();
os.chdir("/storage/emulated/0/Insanity");
ingame = True;
source_dir = os.path.dirname(os.path.abspath(__file__));
screen = pygame.display.set_mode((1280,720));
def get_velo(x,y, dist):
vec1,vect2 = 0,0;
vec1 = y / dist;
vec2 = x / dist;
return vec1,vec2;
class sprite(pygame.sprite.Sprite):
def __init__(self,img, size, pos):
self.img = pygame.image.load(img[1]);
self.size = pygame.transform.scale(self.img, (size[0],size[1])).convert_alpha();
# HITBOX
self.rect = self.size.get_rect(center=pos);
self.pos = self.rect.move(pos);
def display(self):
screen.blit(self.size, self.pos);
HW, HH = 1280/2, 720/2;
AREA = 1280*720;
joystick_body = sprite(["", "circle.png"], [100,100], (0,0));
joystick_control = sprite(["", "circle.png"], [30,30], (0,0));
joystick_body.pos = [0,630];
radius = joystick_body.size.get_rect().center[0];
my_velo = 0;
## PLAYER
player = sprite(["", "player.png"], [100,100], (0,0));
movespeed = 10;
while ingame:
screen.fill((255,255,255));
## JOYSTICK
joystick_body.display();
x, y = pygame.mouse.get_pos();
# CIRCLE COLLISION
v1 = pygame.math.Vector2(0, 630);
v2 = pygame.math.Vector2(x,y);
if v1.distance_to(v2) < radius + radius:
joystick_control.pos = (x,y);
joystick_control.rect.clamp_ip(joystick_body.rect);
vec1,vec2 = x / radius, y / radius# x / v1.distance_to(v2), y / v1.distance_to(v2)
#vec1,vec2 = (x,y, v1.distance_to(v2));
player.pos = (vec1*movespeed,vec2*movespeed);
#joystick_control.pos = joystick_body.pos + (joystick_control.pos - joystick_body.pos).clamped(radius);
else:
joystick_control.pos = (33,664);
player.display();
joystick_control.display();
pygame.display.update();
the video:
https://www.veed.io/view/442d6abd-c072-41bb-98be-be5b1fb1ba42/223fbe52-0cf9-4724-9393-d7a85f9beb68?sharingWidget=true&panel=share
I tried pygame.vector2, rect.move() and the same happened, i felt like i need to use the player.pos x and y but i dont know how i would implement it, if there is a pygame version of godot function (move_and_slide()). I expect to make a working mobile joystick

Related

resize window without border [duplicate]

This question already has an answer here:
ValueError: subsurface rectangle outside surface area
(1 answer)
Closed 1 year ago.
I'm making a platformer, and I want to let the user resize the screen but without borders (so the game isn't fixed ratio). however I don't know the best way to implement this, all my versions are very slow (around 8 fps).
this i was my attempt
def video_resize(self):
self.fit_to_rect = self.blit_surf.get_rect().fit(self.screen.get_rect()) # fit the surface to the screen
self.fit_to_rect.size = self.fit_to_rect.width * self.neutralizerZoom * self.zoom, self.fit_to_rect.height * self.neutralizerZoom * self.zoom # add zoom
def update(self):
scaled = transform.scale(self.blit_surf, (self.fit_to_rect.width, self.fit_to_rect.height)) # scale surface to screen
self.fit_to_rect.topleft = self.screen.get_rect().top + self.cameraPos[0], self.screen.get_rect().left + self.cameraPos[1] # center surface & camera pos
self.mousePos[0] = (mouse.get_pos()[0] / (scaled.get_width() / self.blit_surf.get_width())) - (self.cameraPos[0] / (scaled.get_width() / self.blit_surf.get_width())) # scale x axis mouse pos
self.mousePos[1] = (mouse.get_pos()[1] / (scaled.get_height() / self.blit_surf.get_height())) # scale y axis mouse pos
#scaled = scaled.subsurface(self.fit_to_rect.x, self.fit_to_rect.y, self.fit_to_rect.x + self.fit_to_rect.width, self.fit_to_rect.y + self.fit_to_rect.height)
#self.screen.blit(scaled ,(0, 0)) # blit surface to screen
self.screen.blit(scaled, (self.fit_to_rect.x, self.fit_to_rect.y, self.fit_to_rect.width, self.fit_to_rect.height))
display.flip() # update screen
self.clock.tick(60)
what is the most efficient way to resize the screen like this?
Do not scale the Surface in every frame. Scale the surface once when resizing:
class ...:
def __init__(...):
# [...]
self.scaled_surf = self.blit_surf
def video_resize(self):
self.fit_to_rect = self.blit_surf.get_rect().fit(self.screen.get_rect()) # fit the surface to the screen
self.fit_to_rect.size = self.fit_to_rect.width * self.neutralizerZoom * self.zoom, self.fit_to_rect.height * self.neutralizerZoom * self.zoom # add zoom
self.scaled_surf = transform.scale(self.blit_surf, (self.fit_to_rect.width, self.fit_to_rect.height)) # scale surface to screen
def update(self):
self.fit_to_rect.topleft = self.screen.get_rect().top + self.cameraPos[0], self.screen.get_rect().left + self.cameraPos[1] # center surface & camera pos
self.mousePos[0] = (mouse.get_pos()[0] / (scaled.get_width() / self.blit_surf.get_width())) - (self.cameraPos[0] / (scaled.get_width() / self.blit_surf.get_width())) # scale x axis mouse pos
self.mousePos[1] = (mouse.get_pos()[1] / (scaled.get_height() / self.blit_surf.get_height())) # scale y axis mouse pos
self.screen.blit(self.scaled_surf, (self.fit_to_rect.x, self.fit_to_rect.y, self.fit_to_rect.width, self.fit_to_rect.height))
display.flip() # update screen
self.clock.tick(60)

Using NumPy to improve the performance of an update function in PyGame [duplicate]

I am an aerospace student working on a school project for our python programming course. The assignment is create a program only using Pygame and numpy. I decided to create a wind tunnel simulation that simulates the airflow over a two dimensional wing. I was wondering if there is a more efficient way of doing the computation from a programming perspective. I will explain the program:
I have attached an image here:
The (steady) flow field is modeled using the vortex panel method. Basically, I am using a grid of Nx times Ny points where at each point a velocity (u,v) vector is given. Then using Pygame I map these grid points as circles, so that they resemble an area of influence. The grid points are the grey circles in the following image:
I create N particles and determine their velocities by iterating as follows:
create a list of particles.
create a grid list.
for each gridpoint in grid list:
  for each particle in list of particles:
  if particle A is within the area of influence of grid point n (xn,yn):    particle A its velocity = velocity at grid point n.
Visualize everything in Pygame.
this basic way was the only way I could think of visualizing the flow in Pygame. The simulation works pretty well, but If I increase the number of grid points(increase the accuracy of the flow field), the performance decreases. My question is if there is a more efficient way to do this just using pygame and numpy?
I have attached the code here:
import pygame,random,sys,numpy
from Flow import Compute
from pygame.locals import *
import random, math, sys
#from PIL import Image
pygame.init()
Surface = pygame.display.set_mode((1000,600))
#read the airfoil geometry from a dat file
with open ('./resources/naca0012.dat') as file_name:
x, y = numpy.loadtxt(file_name, dtype=float, delimiter='\t', unpack=True)
#parameters used to describe the flow
Nx=30# 30 column grid
Ny=10#10 row grid
N=20#number of panels
alpha=0#angle of attack
u_inf=1#freestream velocity
#compute the flow field
u,v,X,Y= Compute(x,y,N,alpha,u_inf,Nx,Ny)
#The lists used for iteration
Circles = []
Particles= []
Velocities=[]
#Scaling factors used to properly map the potential flow datapoints into Pygame
magnitude=400
vmag=30
umag=30
panel_x= numpy.multiply(x,magnitude)+315
panel_y= numpy.multiply(-y,magnitude)+308
#build the grid suited for Pygame
grid_x= numpy.multiply(X,magnitude)+300
grid_y= numpy.multiply(Y,-1*magnitude)+300
grid_u =numpy.multiply(u,umag)
grid_v =numpy.multiply(v,-vmag)
panelcoordinates= zip(panel_x, panel_y)
# a grid area
class Circle:
def __init__(self,xpos,ypos,vx,vy):
self.radius=16
self.x = xpos
self.y = ypos
self.speedx = 0
self.speedy = 0
#create the grid list
for i in range(Ny):
for s in range(Nx):
Circles.append(Circle(int(grid_x[i][s]),int(grid_y[i][s]),grid_u[i][s],grid_v[i][s]))
Velocities.append((grid_u[i][s],grid_v[i][s]))
#a particle
class Particle:
def __init__(self,xpos,ypos,vx,vy):
self.image = pygame.Surface([10, 10])
self.image.fill((150,0,0))
self.rect = self.image.get_rect()
self.width=4
self.height=4
self.radius =2
self.x = xpos
self.y = ypos
self.speedx = 30
self.speedy = 0
#change particle velocity if collision with grid point
def CircleCollide(Circle,Particle):
Particle.speedx = int(Velocities[Circles.index((Circle))][0])
Particle.speedy = int(Velocities[Circles.index((Circle))][1])
#movement of particles
def Move():
for Particle in Particles:
Particle.x += Particle.speedx
Particle.y += Particle.speedy
#create particle streak
def Spawn(number_of_particles):
for i in range(number_of_particles):
i=i*(300/number_of_particles)
Particles.append(Particle(0, 160+i,1,0))
#create particles again if particles are out of wake
def Respawn(number_of_particles):
for Particle in Particles:
if Particle.x >1100:
Particles.remove(Particle)
if Particles==[]:
Spawn(number_of_particles)
#Collsion detection using pythagoras and distance formula
def CollisionDetect():
for Circle in Circles:
for Particle in Particles:
if Particle.y >430 or Particle.y<160:
Particles.remove(Particle)
if math.sqrt( ((Circle.x-Particle.x)**2) + ((Circle.y-Particle.y)**2) ) <= (Circle.radius+Particle.radius):
CircleCollide(Circle,Particle)
#draw everything
def Draw():
Surface.fill((255,255,255))
#Surface.blit(bg,(-300,-83))
for Circle in Circles:
pygame.draw.circle(Surface,(245,245,245),(Circle.x,Circle.y),Circle.radius)
for Particle in Particles:
pygame.draw.rect(Surface,(150,0,0),(Particle.x,Particle.y,Particle.width,Particle.height),0)
#pygame.draw.rect(Surface,(245,245,245),(Circle.x,Circle.y,1,16),0)
for i in range(len(panelcoordinates)-1):
pygame.draw.line(Surface,(0,0,0),panelcoordinates[i],panelcoordinates[i+1],3)
pygame.display.flip()
def GetInput():
keystate = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == QUIT or keystate[K_ESCAPE]:
pygame.quit();sys.exit()
def main():
#bg = pygame.image.load("pressure.png")
#bg = pygame.transform.scale(bg,(1600,800))
#thesize= bg.get_rect()
#bg= bg.convert()
number_of_particles=10
Spawn(number_of_particles)
clock = pygame.time.Clock()
while True:
ticks = clock.tick(60)
GetInput()
CollisionDetect()
Move()
Respawn(number_of_particles)
Draw()
if __name__ == '__main__': main()
The code requires another script that computes the flow field itself. It also reads datapoints from a textfile to get the geometry of the wing.
I have not provided these two files, but I can add them if necessary. Thank you in advance.
One bottleneck in your code is likely collision detection. CollisionDetect() computes the distance between each particle and each circle. Then, if a collision is detected, CircleCollide() finds the index of the circle in Circles (a linear search), so that the velocities can be retrieved from the same index in Velocities. Clearly this is ripe for improvement.
First, the Circle class already has the velocities in the speedx/speedy attributes, so Velocities can be eliminated .
Second, because the circles are at fixed locations, you can calculate which circle is closest to any given particle from the position of the particle.
# You may already have these values from creating grid_x etc.
# if not, you only need to calculated them once, because the
# circles don't move
circle_spacing_x = Circles[1].x - Circles[0].x
circle_spacing_y = Circles[Nx].y - Circles[0].y
circle_first_x = Circles[0].x - circle_spacing_x / 2
circle_first_y = Circles[0].y - circle_spacing_y / 2
Then CollisionDetect() becomes:
def CollisionDetect():
for particle in Particles:
if particle.y >430 or particle.y<160:
Particles.remove(particle)
continue
c = (particle.x - circle_first_x) // circle_spacing_x
r = (particle.y - circle_first_y) // circle_spacing_y
circle = Circles[r*Nx + c]
if ((circle.x - particle.x)**2 + (circle.y - particle.y)**2
<= (circle.radius+particle.radius)**2):
particle.speedx = int(circle.speedx)
particle.speedy = int(circle.speedy)
I've tidied up your code and made a few changes, namely adding scope to your classes and introducing a couple more. Without further knowledge of Flow I cannot test this fully, but if you could get back to me I can do some more. I'm assuming here that the 'flow field' can be simulated by the numpy.meshgrid function.
import pygame,numpy,sys
import pygame.locals
import math
class Particle:
def __init__(self,xpos,ypos,vx,vy):
self.size = numpy.array([4,4])
self.radius =2
self.pos = numpy.array([xpos,ypos])
self.speed = numpy.array([30,0])
self.rectangle = numpy.hstack((self.pos,self.size))
def move(self):
self.pos += self.speed
self.rectangle = numpy.hstack((self.pos,self.size))
def distance(self,circle1):
return math.sqrt(numpy.sum((circle1.pos - self.pos)**2))
def collision(self,circle1):
result = False
if self.pos[1] >430 or self.pos[1]<160:
result = True
if self.distance(circle1) <= (circle1.radius+self.radius):
self.speed = circle1.speed
return result
class Particles:
def __init__(self,num_particles):
self.num = num_particles
self.particles =[]
self.spawn()
def spawn(self):
for i in range(self.num):
i=i*(300/self.num)
self.particles.append(Particle(0, 160+i,1,0))
def move(self):
for particle in self.particles:
particle.move()
if particle.pos[0] >1100:
self.particles.remove(particle)
if not self.particles: self.spawn()
def draw(self):
for particle in self.particles:
pygame.draw.rect(Surface,(150,0,0),particle.rectangle,0)
def collisiondetect(self,circle1):
for particle in self.particles:
if particle.collision(circle1):
self.particles.remove(particle)
def GetInput():
keystate = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.locals.QUIT or keystate[pygame.locals.K_ESCAPE]:
pygame.quit()
sys.exit()
#draw everything
def Draw(sw,cir):
Surface.fill((255,255,255))
cir.draw()
for i in range(panelcoordinates.shape[1]):
pygame.draw.line(Surface,(0,0,0),panelcoordinates[0,i-1],panelcoordinates[0,i],3)
sw.draw()
pygame.display.flip()
# a grid area
class Circle:
def __init__(self,xpos,ypos,vx,vy):
self.radius=16
self.pos = numpy.array([xpos,ypos])
self.speed = numpy.array([vx,vy])
class Circles:
def __init__(self,columns,rows):
self.list = []
grid_x,grid_y = numpy.meshgrid(numpy.linspace(0,1000,columns),numpy.linspace(200,400,rows))
grid_u,grid_v = numpy.meshgrid(numpy.linspace(20,20,columns),numpy.linspace(-1,1,rows))
for y in range(rows):
for x in range(columns):
c1= Circle(int(grid_x[y,x]),int(grid_y[y,x]),grid_u[y,x],grid_v[y,x])
self.list.append(c1)
def draw(self):
for circle in self.list:
pygame.draw.circle(Surface,(245,245,245),circle.pos,circle.radius)
def detectcollision(self,parts):
for circle in self.list:
parts.collisiondetect(circle)
if __name__ == '__main__':
#initialise variables
number_of_particles=10
Nx=30
Ny=10
#circles and particles
circles1 = Circles(Nx,Ny)
particles1 = Particles(number_of_particles)
#read the airfoil geometry
panel_x = numpy.array([400,425,450,500,600,500,450,425,400])
panel_y = numpy.array([300,325,330,320,300,280,270,275,300])
panelcoordinates= numpy.dstack((panel_x,panel_y))
#initialise PyGame
pygame.init()
clock = pygame.time.Clock()
Surface = pygame.display.set_mode((1000,600))
while True:
ticks = clock.tick(6)
GetInput()
circles1.detectcollision(particles1)
particles1.move()
Draw(particles1,circles1)
I've also made some a crude stab at drawing a aerofoil, as again I don't have the knowledge of the data file with the coordinates.

Detecting if an arc has been clicked in pygame

I am currently trying to digitalize an boardgame I invented (repo: https://github.com/zutn/King_of_the_Hill). To make it work I need to check if one of the tiles (the arcs) on this board have been clicked. So far I have not been able to figure a way without giving up the pygame.arc function for drawing. If I use the x,y position of the position clicked, I can't figure a way out to determine the exact outline of the arc to compare to. I thought about using a color check, but this would only tell me if any of the tiles have been clicked. So is there a convenient way to test if an arc has been clicked in pygame or do I have to use sprites or something completely different? Additionally in a later step units will be included, that are located on the tiles. This would make the solution with the angle calculation postet below much more diffcult.
This is a simple arc class that will detect if a point is contained in the arc, but it will only work with circular arcs.
import pygame
from pygame.locals import *
import sys
from math import atan2, pi
class CircularArc:
def __init__(self, color, center, radius, start_angle, stop_angle, width=1):
self.color = color
self.x = center[0] # center x position
self.y = center[1] # center y position
self.rect = [self.x - radius, self.y - radius, radius*2, radius*2]
self.radius = radius
self.start_angle = start_angle
self.stop_angle = stop_angle
self.width = width
def draw(self, canvas):
pygame.draw.arc(canvas, self.color, self.rect, self.start_angle, self.stop_angle, self.width)
def contains(self, x, y):
dx = x - self.x # x distance
dy = y - self.y # y distance
greater_than_outside_radius = dx*dx + dy*dy >= self.radius*self.radius
less_than_inside_radius = dx*dx + dy*dy <= (self.radius- self.width)*(self.radius- self.width)
# Quickly check if the distance is within the right range
if greater_than_outside_radius or less_than_inside_radius:
return False
rads = atan2(-dy, dx) # Grab the angle
# convert the angle to match up with pygame format. Negative angles don't work with pygame.draw.arc
if rads < 0:
rads = 2 * pi + rads
# Check if the angle is within the arc start and stop angles
return self.start_angle <= rads <= self.stop_angle
Here's some example usage of the class. Using it requires a center point and radius instead of a rectangle for creating the arc.
pygame.init()
black = ( 0, 0, 0)
width = 800
height = 800
screen = pygame.display.set_mode((width, height))
distance = 100
tile_num = 4
ring_width = 20
arc = CircularArc((255, 255, 255), [width/2, height/2], 100, tile_num*(2*pi/7), (tile_num*(2*pi/7))+2*pi/7, int(ring_width*0.5))
while True:
fill_color = black
for event in pygame.event.get():
# quit if the quit button was pressed
if event.type == pygame.QUIT:
pygame.quit(); sys.exit()
x, y = pygame.mouse.get_pos()
# Change color when the mouse touches
if arc.contains(x, y):
fill_color = (200, 0, 0)
screen.fill(fill_color)
arc.draw(screen)
# screen.blit(debug, (0, 0))
pygame.display.update()

How to add a collision detector to my game of pong in pygame

I am having trouble getting a collision detector to work for my game of pong without having to change all of classes (sprite, render).
I've seen some useful threads here on StackOverflow but I can't seem to get them to work.
#Create a class named sprite to use for the paddles and the ball.
class Sprite():
def __init__(self,x,y,width,height,color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color= (255,255,255)
#attirbute for drawing the sprite(s) to the screen
def render(self):
pygame.draw.rect(screen,self.color,(self.x,self.y,self.width,self.height))
#Create the sprites
Paddle1 = Sprite(50,175,25,150,color[0])
Paddle2 = Sprite(650,175,25,150,color[1])
Ball = Sprite(300,250,25,25, color[2])
#Set the Sprite's color(s)
Paddle1.color = color[0]
Paddle2.color = color[1]
Ball.color = color[2]
#Variables used for moving the paddles
moveY1,moveY2=0,0
#### Spot where my collision detector goes####
#### Code for drawing and moving the paddles####
Paddle1.y += moveY1
Paddle1.render()
Paddle2.y += moveY2
Paddle2.render()
#Draw the Ball
Ball.render()
This is a working snippet for a Pong game I made with pygame. I also made for the second bumper, but ommited to save space, since its pretty much the same thing
def check_bumpers_collision(self):
if (self.ball.pos_x < self.bumper_one.pos_x + self.bumper_one.width and
self.ball.pos_x + self.ball.size > self.bumper_one.pos_x and
self.ball.pos_y < self.bumper_one.pos_y + self.bumper_one.height and
self.ball.pos_y + self.ball.size > self.bumper_one.pos_y):
# Change Ball X moving direction
self.ball.speed_x *= -1
# Change Y ball Speed
if self.bumper_one.moving_up:
self.ball.speed_y -= 5
elif self.bumper_one.moving_down:
self.ball.speed_y += 5

Debugging simple Ping-Pong game?

I've been programming a simple ping-pong game using Python's Pygame as run through Livewires. I've posted the question and a similar sample game code that runs perfectly as not everyone here will be versed in livewires and/or pygame.
Here's the code that has bugs on it. What happens is the window opens, and the "Ball" object works well and falls of the screen (as it should, it's incomplete), and the "Slab" object is gets stuck to wherever the mouse initially is. Here it is:
from livewires import games, color
games.init (screen_width = 640, screen_height = 480, fps = 50)
class Ball (games.Sprite):
def iMove (self):
self.dx = -self.dx
self.dy = -self.dy
class Slab (games.Sprite):
def mouse_moves (self):
self.x = games.mouse.x
self.y = games.mouse.y
self.iCollide()
def iCollide (self):
for Ball in overlapping_sprites:
Ball.iMove()
def main():
#Backgrounds
pingpongbackground = games.load_image ("pingpongbackground.jpg", transparent = False)
games.screen.background = pingpongbackground
#Ball: Initializing object and setting speed.
ballimage = games.load_image ("pingpongball.jpg")
theball = Ball (image = ballimage,
x = 320,
y = 240,
dx = 2,
dy = 2)
games.screen.add(theball)
#Paddle: Initializing ping pong object and setting initial poisition to the initial mouse position
slabimage = games.load_image ("pingpongpaddle.jpg")
theslab = Slab (image = slabimage,
x = games.mouse.x,
y = games.mouse.y)
games.screen.add(theslab)
games.mouse.is_visible = False
games.screen.event_grab = True
games.screen.mainloop()
main ()
And here's a piece of similar, functioning code:
# Slippery Pizza Program
# Demonstrates testing for sprite collisions
from livewires import games
import random
games.init(screen_width = 640, screen_height = 480, fps = 50)
class Pan(games.Sprite):
"""" A pan controlled by the mouse. """
def update(self):
""" Move to mouse position. """
self.x = games.mouse.x
self.y = games.mouse.y
self.check_collide()
def check_collide(self):
""" Check for collision with pizza. """
for pizza in self.overlapping_sprites:
pizza.handle_collide()
class Pizza(games.Sprite):
"""" A slippery pizza. """
def handle_collide(self):
""" Move to a random screen location. """
self.x = random.randrange(games.screen.width)
self.y = random.randrange(games.screen.height)
def main():
wall_image = games.load_image("wall.jpg", transparent = False)
games.screen.background = wall_image
pizza_image = games.load_image("pizza.bmp")
pizza_x = random.randrange(games.screen.width)
pizza_y = random.randrange(games.screen.height)
the_pizza = Pizza(image = pizza_image, x = pizza_x, y = pizza_y)
games.screen.add(the_pizza)
pan_image = games.load_image("pan.bmp")
the_pan = Pan(image = pan_image,
x = games.mouse.x,
y = games.mouse.y)
games.screen.add(the_pan)
games.mouse.is_visible = False
games.screen.event_grab = True
games.screen.mainloop()
# kick it off!
main()
Any insight at all would be greatly appreciated!
I don't know your framework, but to keep the slab from "getting stuck" you need to update its location when the mouse is moved.
Here you initialize it:
theslab = Slab (image = slabimage,
x = games.mouse.x,
y = games.mouse.y)
Then here you add it to the game:
games.screen.add(theslab)
Presumably, the game would then call this function whenever the mouse moves:
def mouse_moves (self):
self.x = games.mouse.x
self.y = games.mouse.y
self.iCollide()
But that is either not happening, or the screen is not getting updated.
So you should find out, by doing this:
def mouse_moves (self):
print "mouse_moves: ", str(games.mouse.x), str(games.mouse.y)
self.x = games.mouse.x
self.y = games.mouse.y
self.iCollide()
If you see the output of the print statement happening when the mouse moves, you're probably not updating the screen, you'll need to check the framework docs. But I don't think that's the case. I think you are not updating the game when the mouse moves. I would imagine the framework has some sort of onMouseMove type event that you need to hook into, to allow you to update the game state (i.e. call mouse_moves()) when mouse movement occurs. Then, the next time the screen is updated, you should check for changes (invalidate the objects, mark them as dirty) and if they are dirty, update their part of the screen then mark them clean again.
Just put this update method in the slab class:
def update(self):
self.x=games.mouse.x
self.y=games.mouse.y
It will automatically run once every fiftieth of a second (your update speed). Currently, you just start the slab at the position of the mouse, and leave it there.

Categories

Resources