Trying To Make Screen Center To Player In Pygame Simple 2D Platformer
I am creating a simple 2D platformer in Pygame. In this project I have been trying to use classes much more for good practice. My current problem is that I am trying to make the sc
Solution 1:
You should move the camera like this:
# at the beginning: set camera
camera = pygame.math.Vector2((0, 0))
# in the main loop: adjust the camera position to center the player
camera.x = player.x_pos - resx / 2
camera.y = player.y_pos - resy / 2
# in each sprite class: move according to the camera instead of changing the sprite position
pos_on_the_screen = (self.x_pos - camera.x, self.y_pos - camera.y)
- The camera follows the player, and places itself so that the player is in the center of the screen
- The position of each sprite never changes, this is a very bad idea to constantly change the position of the sprites.
- Each sprite is drawn on the screen depending of the camera
To reduce lag, you should display each sprite only if it is visible:
screen_rect = pygame.Rect((0, 0), (resx, resy))
sprite_rect = pygame.Rect((self.x_pos - camera.x, self.y_pos - camera.y), sprite_image.get_size())
if screen_rect.colliderect(sprite_rect):
# render if visible
Here is a screenshot of a moving background in a game I made, using the same method:
Here I move the camera more smoothly. Basically I use this method:
speed = 1
distance_x = player.x_pos - camera.x
distance_y = player.y_pos - camera.y
camera.x = (camera.x * speed + distance_x) / (speed + 1)
camera.y = (camera.y * speed + distance_y) / (speed + 1)
And I change speed
according to the FPS.
Post a Comment for "Trying To Make Screen Center To Player In Pygame Simple 2D Platformer"