Home > database >  I need to constantly move a character from the left to the right of the screen without touching anyt
I need to constantly move a character from the left to the right of the screen without touching anyt

Time:11-02

I tried diferent technics but still don't get it. This function is in a class Player() so it moves the player from left to right automatically

    def move(self):
        dx = 0
        dy = 0
    
        # CHECKING THE RECT IF HAS HIT THE BORDERS
        if self.rect.left   dx < 0:
            pass
            # CHANGING DIRECTION TO RIGHT
        if self.rect.right   dx > SCREEN_WIDHT:
            pass
            # CHANING DIRECTION TO LEFT
        self.rect.x  = dx
        self.rect.y  = dy

i don't have any ideas on how to make this loop

CodePudding user response:

Perhaps we can implement it like this

import random as rnd
import time
class Player:
    dx=1
    dy=1
    maxx=100
    maxy=100
    def __init__(self):
        self.x=rnd.randint(1,100)
        self.y=rnd.randint(1,100)
        self.dir_x=1
        self.dir_y=1
    def move(self):
        self.x =Player.dx*self.dir_x
        self.y =Player.dy*self.dir_y
        
        if self.x Player.dx*self.dir_x>Player.maxx or self.x Player.dx*self.dir_x<0:
            self.dir_x=-self.dir_x
        if self.y Player.dy*self.dir_y>Player.maxy or self.y Player.dy*self.dir_y<0:
            self.dir_y=-self.dir_y

    def __str__(self):
        return "[X : {} and Y : {}]".format(self.x, self.y)

p = Player()
while True:
    p.move()
    print(p, end="\r")
    time.sleep(0.1)

CodePudding user response:

You don't nee any extra loop. Use the application loop. Redraw the entire scene in each frame. Change the position of the object slightly in each frame. Since the object is drawn at a different position in each frame, the object appears to move smoothly. Limit frames per second to limit CPU usage and control the speed of the object with pygame.time.Clock.tick.
Change the direction when the plyer hits the border:

if self.rect.left   self.dx < 0:
    self.dx *= -1
if self.rect.right   self.dx > SCREEN_WIDHT:
    self.dx *= -1

Minimal example:

import pygame

pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

class Player:
    def __init__(self):
        self.rect = pygame.Rect(0, 180, 40, 40)
        self.dx = 5
    
    def move(self):
        if self.rect.left   self.dx < 0:
            self.dx *= -1
        if self.rect.right   self.dx > window.get_width():
            self.dx *= -1
        self.rect.x  = self.dx
        
player = Player()

run = True
while run:
    clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    player.move()
    
    window.fill(0)
    pygame.draw.rect(window, (255, 0, 0), player.rect)
    pygame.display.flip()

pygame.quit()
exit()
  • Related