How do i make it so that when the player touches the platform, he does not fall through? when the game starts the player falls onto the platform. But right now he just falls through. I have implemented things such as velocity, gravity, and acceleration.
import pygame as pg
import os
# create a variable for pg.math.Vector2
vec = pg.math.Vector2
TITLE = "Jumping 1"
WIDTH = 800
HEIGHT = 600
clock = pg.time.Clock()
FPS = 60
GREEN = (0, 255, 0)
LIGHTBLUE = (50, 200, 250)
RED = (255, 0, 0)
# Player properties
PLAYER_ACC = 0.5
PLAYER_FRICTION = -0.12
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, "img")
class Player(pg.sprite.Sprite):
def __init__(self):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((50, 50))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.center = ((WIDTH / 2, HEIGHT / 2))
# position, velocity, acceleration
self.pos = vec(WIDTH / 2, HEIGHT / 2)
self.vel = vec(0, 0)
self.acc = vec(0, 0)
def update(self):
self.acc = vec(0, 0.5)
keystate = pg.key.get_pressed()
if keystate[pg.K_LEFT]:
self.acc.x = -PLAYER_ACC
if keystate[pg.K_RIGHT]:
self.acc.x = PLAYER_ACC
# apply friction
self.acc.x += self.vel.x * PLAYER_FRICTION
# equations of motion
self.vel += self.acc
self.pos += self.vel + 0.5 * self.acc
# wrap around the sides of the screen
if self.pos.x > WIDTH:
self.pos.x = 0
if self.pos.x < 0:
self.pos.x = WIDTH
self.rect.midbottom = self.pos
player = Player()
class Platform(pg.sprite.Sprite):
def __init__(self):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((WIDTH, 50))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.center = ((WIDTH / 2, HEIGHT - 25))\
platform = Platform()
def game_loop():
pg.init()
screen = pg.display.set_mode((WIDTH, HEIGHT))
pg.display.set_caption(TITLE)
all_sprites = pg.sprite.Group()
all_sprites.add(player, platform)
running = True
while running:
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
all_sprites.update()
screen.fill(LIGHTBLUE)
all_sprites.draw(screen)
pg.display.flip()
clock.tick(FPS)
pg.quit()
game_loop()