I have been trying to create a mario type 2d side scrolling platformer using python and the pygame module. I used tutorials from programarcadegames to code the platforms and player, i just can't figure out how to implement enemies that spawn at a particular x and y coordinate and add them as a collide-able sprite (That "kills" the player in one hit)?
The tutorials code is below:
http://programarcadegames.com/python_examples/show_file.php?file=platform_moving.py
Ive tried creating the basic class for the enemy sprite and making it move in a backwards and forwards motion but positioning it is my main problem.
Here's my code: (The enemy does glitch a bit when the level is scrolled)
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
width = 30
height = 30
self.image = pygame.Surface([width, height])
self.image.fill(BLUE)
# Set a reference to the image rect.
self.rect = self.image.get_rect()
# Set speed vector of player
self.change_x = random.randint(3, 4)
self.change_y = 0
def update(self):
self.rect.centerx += self.change_x
if self.rect.right <= 0 or self.rect.left >= 100:
self.change_x *= -1
for the collision with the player i recommend you something like this:
#in your gameloop
playerEnemyCollision = pygame.sprite.spritecollide(player, enemies, False)
"enemies" needs to be a sprite-group.To create a sprite group:
#outside your gameloop
enemies = pygame.sprite.Group()
To create a new Enemy and add it to the group, just typ:
#outside your gameloop
en = Enemy()
en.rect.x = XX #set your Enemies x-Position
en.rect.y = YY #set your Enemies y-Position
en.add(enemies) #adds the enemy "en" to the sprite-group "enemies"
Now you can check for a collision with:
#in your gameloop
if playerEnemyCollision:
#your "kill-player-code" goes her
#Example:
player.kill()
It is at the most time not such a good idea to change a sprite's location for normal movement outside your "Enemy-Class". I hope i could help you with your question. Twistios
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.