Python Forum
[PyGame] how to make objects move at a precise amount of time? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Game Development (https://python-forum.io/forum-11.html)
+--- Thread: [PyGame] how to make objects move at a precise amount of time? (/thread-28756.html)



how to make objects move at a precise amount of time? - Zhaleh - Aug-02-2020

Hi everybody. I'm quite a beginner in programming. I wrote a code that produces an image moving left and right until it hits the walls and change direction. After each collision to the wall, I want it to move at a different speed and this time should be exact in my work. So for my project, I need it to hit the walls 6 times with inter collision times being 500ms, 500ms, 1000ms, 750ms, and 250ms. My code doesn't produce exact times. What should I do to have these precise timings between collisions?
Here is my code:

import pygame 
pygame.init()
screen=pygame.display.set_mode((800,600)) 

pygame.display.set_caption('visual rhythm')
icon=pygame.image.load("song.png")
pygame.display.set_icon(icon)

playerImg=pygame.image.load('spaceship.png')
playerX=370
playerY=400
def player(x,y):
    screen.blit(playerImg,(int(x),int(y)))

acceleration=[0.5, -0.5 , 1 , -0.7 , 0.3]
count=0
count2=0
while count2<len(acceleration):
    screen.fill((0,255,0))
    playerX+=acceleration[count]
    player(playerX,playerY)
    pygame.display.update()
    if playerX>=746 or playerX<1:
        count+=1
        count2+=1



RE: how to make objects move at a precise amount of time? - Knight18 - Aug-02-2020

1. Create a list with those values.
2. Create a variable that will act as the index (or counter) for the list.
3. Every time a collision occurs, update the variable and use the variable on the list to retrieve the next interval. Like list[index].

Let me know if you understood.


RE: how to make objects move at a precise amount of time? - Zhaleh - Aug-02-2020

I'm not sure if I understand you well but this is how I changed my code. Would you look at that and tell me if this is what you meant? The values in the list 'speed' are going to give me the time intervals I want between collistions: 500, 500, 1000, 750, 250 ms
import pygame 
pygame.init()
screen=pygame.display.set_mode((1000,1000)) 

pygame.display.set_caption('visual rhythm')
icon=pygame.image.load("song.png")
pygame.display.set_icon(icon)

playerImg=pygame.image.load('spaceship.png')
playerX=370
playerY=400
def player(x,y):
    screen.blit(playerImg,(int(x),int(y)))

speed=[4000, -2000 , 2000 , -1000 , 1333 , -4000]
count=0
count2=0
clock=pygame.time.Clock()
while count2<len(speed):
    screen.fill((0,255,0))
    milli=clock.tick()
    seconds=milli/1000.0
    dm=seconds*speed[count]
    playerY+=dm
    player(playerX,playerY)
    pygame.display.update()
    if playerY>=946 or playerY<1:
        count+=1
        count2+=1