Oct-19-2024, 01:31 PM
I'll post more code if needed, but I'm a bit confused. I'm currently using pygame for this.
I use randint() to spawn objects at random intervals, and then after that, move them in a random direction (up, down, left or right) at a different random interval. My problem is that with how I've coded it, the objects snap/teleport whatever the distance is, rather than move there at a fast speed that I set. I can't seem to figure out how to make them move gradually to a random destination.
This was my final attempt. My previous attempt was much more basic, but there was no difference unfortunately.
I use randint() to spawn objects at random intervals, and then after that, move them in a random direction (up, down, left or right) at a different random interval. My problem is that with how I've coded it, the objects snap/teleport whatever the distance is, rather than move there at a fast speed that I set. I can't seem to figure out how to make them move gradually to a random destination.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# directions for the enemy object to move in directions = [( 1 , 0 ), ( - 1 , 0 ), ( 0 , 1 ), ( 0 , - 1 )] # spawn an enemy in a random spot def spawn_enemy_object(): x = randint( 0 , window.get_width() - object_size) y = randint( 0 , window.get_height() - object_size) enemy_direction = choice(directions) return { 'rect' : pygame.Rect(x, y, object_size, object_size), 'enemy_direction' : enemy_direction, 'enemy_move_time' : pygame.time.get_ticks() + randint( 5000 , 8000 ), 'enemy_moves_left' : 2 , 'is_enemy_moving' : True , # start moving 'speed' : 50 # speed of the enemy rectangle object } elif event. type = = move_event: current_time = pygame.time.get_ticks() for obj in objects[:]: if current_time > = obj[ 'enemy_move_time' ]: if obj[ 'is_enemy_moving' ]: if obj[ 'enemy_moves_left' ] > 0 : obj[ 'rect' ].x + = obj[ 'enemy_direction' ][ 0 ] * obj[ 'speed' ] obj[ 'rect' ].y + = obj[ 'enemy_direction' ][ 1 ] * obj[ 'speed' ] obj[ 'enemy_move_time' ] = current_time + randint( 5000 , 9000 ) obj[ 'enemy_moves_left' ] - = 1 else : |