Я создаю платформер, используя физический движок pymunk и pygame для его отображения.
Мне интересно, как я могу сделать так, чтобы игрок придерживался движения платформа? Прямо сейчас, если я не буду следовать за платформой, перемещая игрока, игрок останется на том же месте, пока стоит на платформе, а затем упадет, когда платформа уйдет.
< img alt="введите здесь описание изображения" src="https://i.sstatic.net/EDtB7jKZ.gif" />
Это код, который я использую:
#Pymunk Platformer:
import pygame
import pymunk
import sys
from UtilityFunctions import*
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Platformer Game')
clock = pygame.time.Clock()
space = pymunk.Space()
space.gravity = (0, 900) # Gravity pulls objects downwards
class Player(pygame.sprite.Sprite):
def __init__(self, x, y, width=30, height=30):
super().__init__()
self.image = pygame.Surface((30, 30), pygame.SRCALPHA).convert_alpha()
self.image.fill((255, 0, 0)) # Red square for player
self.rect = self.image.get_rect(center=(x, y))
# Pymunk physics body
mass = 1
self.width, self.height = width, height
# inertia = pymunk.moment_for_box(mass, (width, height))
# Setting the inertia to infinity makes it so that the rectangle does not rotate when colliding with other objects:
inertia = float("inf")
self.body = pymunk.Body(mass, inertia)
self.body.position = x, y
self.shape = pymunk.Poly.create_box(self.body, (width, height))
self.shape.collision_type = 1 # Player collision type
self.shape.friction = 1
space.add(self.body, self.shape)
self.on_ground = False
self.angle = 0
self.start_position = (x, y)
def update(self):
self.rect.center = self.body.position
self.angle = ConvertRadiansToDegrees(self.body.angle)
if self.body.position.y > 2000:
self.body.position = self.start_position
self.body.velocity = (0,0)
def jump(self):
if self.on_ground:
self.body.velocity = (self.body.velocity.x, -300) # Jump velocity
self.on_ground = False
class Platform(pygame.sprite.Sprite):
def __init__(self, x, y, width, height):
super().__init__()
self.image = pygame.Surface((width, height))
self.image.fill((0, 255, 0)) # Green rectangle for platforms
self.rect = self.image.get_rect(topleft=(x, y))
# Static body for platforms
self.body = pymunk.Body(body_type=pymunk.Body.STATIC)
self.body.position = x + width / 2, y + height / 2 # Center of the platform
shape = pymunk.Poly.create_box(self.body, (width, height))
shape.collision_type = 2 # Platform collision type
shape.friction = 0.5
space.add(self.body, shape)
def update(self):
pass # Platforms don't need to update their position
class MovingPlatform(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, range, speed):
super().__init__()
self.image = pygame.Surface((width, height))
self.image.fill((0, 255, 0)) # Green rectangle for platforms
self.rect = self.image.get_rect(topleft=(x, y))
# Change to KINEMATIC instead of STATIC
self.body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
self.body.position = x+width/2, y+height/2 # Center of the platform
self.shape = pymunk.Poly.create_box(self.body, (width, height))
self.shape.collision_type = 2 # Platform collision type
self.shape.friction = 1.5
space.add(self.body, self.shape)
self.range = range # How far it moves
self.speed = speed # Speed of movement
self.direction = 1 # 1 for moving right/up, -1 for left/down
self.start_x, self.start_y = x, y
def update(self):
# Move the platform back and forth
if self.body.position.x > self.start_x + self.range and self.direction == 1:
self.direction = -1 # Reverse direction at edges
if self.body.position.x < self.start_x and self.direction == -1:
self.direction = 1 # Reverse direction at edges
self.body.position = (self.body.position.x + self.direction * self.speed, self.body.position.y)# Set surface velocity to match platform movement
self.shape.surface_velocity = (self.direction * self.speed, 0)
self.rect.center = self.body.position
def player_on_ground(arbiter, space, data):
for shape in arbiter.shapes:
if shape == player.shape:
player.on_ground = True
return True
return False
handler = space.add_collision_handler(1, 2) # Player and Platform
handler.begin = player_on_ground
# Create player and platforms
player = Player(350, 200)
platforms = pygame.sprite.Group()
for _ in range(3): # Create three platforms
platforms.add(Platform(100 + _ * 200, HEIGHT - 200, 100, 20))
for i in range(2):
platforms.add(Platform(20 + i * 300, HEIGHT - 300, 200, 20))
for i in range(2):
ptfm = MovingPlatform(200 + i * 200, HEIGHT - 370, 40, 20, range=100, speed=1)
platforms.add(ptfm)
all_sprites = pygame.sprite.Group(*platforms)
direction = "right"
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.body.velocity = (-150, player.body.velocity.y) # Move left
if keys[pygame.K_RIGHT]:
player.body.velocity = (150, player.body.velocity.y) # Move right
if keys[pygame.K_SPACE]:
player.jump()
# Update physics
space.step(1 / 60.0)
# Update sprites
all_sprites.update()
player.update()
# Draw
screen.fill((0, 0, 0))
all_sprites.draw(screen)
rotated_image = pygame.transform.rotate(player.image, player.angle)
width, height = rotated_image.get_size()
half_width, half_height = int(width/2), int(height/2)
x, y = player.rect.center
screen.blit(rotated_image, [x - half_width, y - half_height])
# print(player.body.position)
pygame.display.flip()
clock.tick(50)
pygame.quit()
sys.exit()
Подробнее здесь: https://stackoverflow.com/questions/792 ... unk-python
Как заставить игрока прилипнуть к движущейся платформе с помощью pymunk-python? ⇐ Python
Программы на Python
1733238122
Anonymous
Я создаю платформер, используя физический движок pymunk и pygame для его отображения.
Мне интересно, как я могу сделать так, чтобы игрок придерживался движения платформа? Прямо сейчас, если я не буду следовать за платформой, перемещая игрока, игрок останется на том же месте, пока стоит на платформе, а затем упадет, когда платформа уйдет.
< img alt="введите здесь описание изображения" src="https://i.sstatic.net/EDtB7jKZ.gif" />
Это код, который я использую:
#Pymunk Platformer:
import pygame
import pymunk
import sys
from UtilityFunctions import*
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Platformer Game')
clock = pygame.time.Clock()
space = pymunk.Space()
space.gravity = (0, 900) # Gravity pulls objects downwards
class Player(pygame.sprite.Sprite):
def __init__(self, x, y, width=30, height=30):
super().__init__()
self.image = pygame.Surface((30, 30), pygame.SRCALPHA).convert_alpha()
self.image.fill((255, 0, 0)) # Red square for player
self.rect = self.image.get_rect(center=(x, y))
# Pymunk physics body
mass = 1
self.width, self.height = width, height
# inertia = pymunk.moment_for_box(mass, (width, height))
# Setting the inertia to infinity makes it so that the rectangle does not rotate when colliding with other objects:
inertia = float("inf")
self.body = pymunk.Body(mass, inertia)
self.body.position = x, y
self.shape = pymunk.Poly.create_box(self.body, (width, height))
self.shape.collision_type = 1 # Player collision type
self.shape.friction = 1
space.add(self.body, self.shape)
self.on_ground = False
self.angle = 0
self.start_position = (x, y)
def update(self):
self.rect.center = self.body.position
self.angle = ConvertRadiansToDegrees(self.body.angle)
if self.body.position.y > 2000:
self.body.position = self.start_position
self.body.velocity = (0,0)
def jump(self):
if self.on_ground:
self.body.velocity = (self.body.velocity.x, -300) # Jump velocity
self.on_ground = False
class Platform(pygame.sprite.Sprite):
def __init__(self, x, y, width, height):
super().__init__()
self.image = pygame.Surface((width, height))
self.image.fill((0, 255, 0)) # Green rectangle for platforms
self.rect = self.image.get_rect(topleft=(x, y))
# Static body for platforms
self.body = pymunk.Body(body_type=pymunk.Body.STATIC)
self.body.position = x + width / 2, y + height / 2 # Center of the platform
shape = pymunk.Poly.create_box(self.body, (width, height))
shape.collision_type = 2 # Platform collision type
shape.friction = 0.5
space.add(self.body, shape)
def update(self):
pass # Platforms don't need to update their position
class MovingPlatform(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, range, speed):
super().__init__()
self.image = pygame.Surface((width, height))
self.image.fill((0, 255, 0)) # Green rectangle for platforms
self.rect = self.image.get_rect(topleft=(x, y))
# Change to KINEMATIC instead of STATIC
self.body = pymunk.Body(body_type=pymunk.Body.KINEMATIC)
self.body.position = x+width/2, y+height/2 # Center of the platform
self.shape = pymunk.Poly.create_box(self.body, (width, height))
self.shape.collision_type = 2 # Platform collision type
self.shape.friction = 1.5
space.add(self.body, self.shape)
self.range = range # How far it moves
self.speed = speed # Speed of movement
self.direction = 1 # 1 for moving right/up, -1 for left/down
self.start_x, self.start_y = x, y
def update(self):
# Move the platform back and forth
if self.body.position.x > self.start_x + self.range and self.direction == 1:
self.direction = -1 # Reverse direction at edges
if self.body.position.x < self.start_x and self.direction == -1:
self.direction = 1 # Reverse direction at edges
self.body.position = (self.body.position.x + self.direction * self.speed, self.body.position.y)# Set surface velocity to match platform movement
self.shape.surface_velocity = (self.direction * self.speed, 0)
self.rect.center = self.body.position
def player_on_ground(arbiter, space, data):
for shape in arbiter.shapes:
if shape == player.shape:
player.on_ground = True
return True
return False
handler = space.add_collision_handler(1, 2) # Player and Platform
handler.begin = player_on_ground
# Create player and platforms
player = Player(350, 200)
platforms = pygame.sprite.Group()
for _ in range(3): # Create three platforms
platforms.add(Platform(100 + _ * 200, HEIGHT - 200, 100, 20))
for i in range(2):
platforms.add(Platform(20 + i * 300, HEIGHT - 300, 200, 20))
for i in range(2):
ptfm = MovingPlatform(200 + i * 200, HEIGHT - 370, 40, 20, range=100, speed=1)
platforms.add(ptfm)
all_sprites = pygame.sprite.Group(*platforms)
direction = "right"
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player.body.velocity = (-150, player.body.velocity.y) # Move left
if keys[pygame.K_RIGHT]:
player.body.velocity = (150, player.body.velocity.y) # Move right
if keys[pygame.K_SPACE]:
player.jump()
# Update physics
space.step(1 / 60.0)
# Update sprites
all_sprites.update()
player.update()
# Draw
screen.fill((0, 0, 0))
all_sprites.draw(screen)
rotated_image = pygame.transform.rotate(player.image, player.angle)
width, height = rotated_image.get_size()
half_width, half_height = int(width/2), int(height/2)
x, y = player.rect.center
screen.blit(rotated_image, [x - half_width, y - half_height])
# print(player.body.position)
pygame.display.flip()
clock.tick(50)
pygame.quit()
sys.exit()
Подробнее здесь: [url]https://stackoverflow.com/questions/79248121/how-do-i-make-the-player-stick-to-a-moving-platform-using-pymunk-python[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия