BetterNot
BetterNot

Reputation: 117

How to make my sprite bounce off the boundaries in pygame

So basically I want to try to make the Sprite bounce off the boundaries of my pygame screen (1920, 1020) but it doesn't work along with the player movement. For me, either have the player movement or the bounce. The code below includes the player movement but not the bounce. But I want bottth... Any ideas? Thanks! Credits to Rabbid76 and Ann Zen.

Code:

import pygame
import os
import random
import math
import winsound
# winsound.PlaySound("explosion.wav", winsound.SND_ALIAS)

os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0, 30)
wn = pygame.display.set_mode((1920, 1020))
clock = pygame.time.Clock()
icon = pygame.image.load('Icon.png')
pygame.image.load('Sprite0.png')
pygame.image.load('Sprite0.png')
pygame.display.set_icon(icon)
pygame.display.set_caption('DeMass.io')




class Player(pygame.sprite.Sprite):
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        z = random.randint(1, 2)
        if z == 2:
            self.original_image = pygame.image.load('Sprite0.png')
        else:
            self.original_image = pygame.image.load('Sprite3.png')
        self.image = self.original_image
        self.rect = self.image.get_rect(center=(x, y))
        self.direction = pygame.math.Vector2((0, -1))
        self.velocity = 5
        self.position = pygame.math.Vector2(x, y)


    def point_at(self, x, y):
        self.direction = pygame.math.Vector2(x, y) - self.rect.center
        if self.direction.length() > 0:
            self.direction = self.direction.normalize()
        angle = self.direction.angle_to((0, -1))
        self.image = pygame.transform.rotate(self.original_image, angle)
        self.rect = self.image.get_rect(center=self.rect.center)

    def move(self, x, y):
        self.position -= self.direction * y * self.velocity
        self.position += pygame.math.Vector2(-self.direction.y, self.direction.x) * x * self.velocity
        self.rect.center = round(self.position.x), round(self.position.y)


    def reflect(self, NV):
        self.direction = self.direction.reflect(pygame.math.Vector2(NV))

    def update(self):
        self.position += self.direction * self.velocity
        self.rect.center = round(self.position.x), round(self.position.y)

    def hit(self, player):
        distance = math.sqrt(math.pow(self.xcor() - player.xcor(), 2) + math.pow(self.ycor() - player.ycor(), 2))
        if distance < 20:
            return True
        else:
            return False



player = Player(200, 200)



while True:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        elif event.type == pygame.MOUSEMOTION:
            player.point_at(*event.pos)




    keys = pygame.key.get_pressed()
    if keys[pygame.K_w] or keys[pygame.K_UP]:
        player.move(0, -1)






    wn.fill((255, 255, 255))
    all_sprites.draw(wn)
    pygame.display.update()

Upvotes: 1

Views: 693

Answers (2)

Rabbid76
Rabbid76

Reputation: 210978

If you want to restrict the player to a rectangular area, you must restrict the player's position and rect attributes. Add an additional argument clamp_rect to the method move. If the player's position exceeds the boundaries of the rectangle, move the player inside the rectangle:

class Player(pygame.sprite.Sprite):
    # [...]

    def move(self, x, y, clamp_rect):
        self.position -= self.direction * y * self.velocity
        self.position += pygame.math.Vector2(-self.direction.y, self.direction.x) * x * self.velocity
        self.rect.center = round(self.position.x), round(self.position.y)

        if self.rect.left < clamp_rect.left:
            self.rect.left = clamp_rect.left
            self.position.x = self.rect.centerx
        if self.rect.right > clamp_rect.right:
            self.rect.right = clamp_rect.right
            self.position.x = self.rect.centerx
        if self.rect.top < clamp_rect.top:
            self.rect.top = clamp_rect.top
            self.position.y = self.rect.centery
        if self.rect.bottom > clamp_rect.bottom:
            self.rect.bottom = clamp_rect.bottom
            self.position.y = self.rect.centery

Pass the window rectangle (wn.get_rect()) to move:

while True:
    # [...]

    keys = pygame.key.get_pressed()
    if keys[pygame.K_w] or keys[pygame.K_UP]:
        player.move(0, -1, wn.get_rect())

    # [...]

Upvotes: 1

Shark Coding
Shark Coding

Reputation: 143

make a bounce animation. define your boundaries and when you hit a wall make the animation run. (for this example you have to predefine hit_wall and have an if statement to check if it is on your boundaries)
Example:

if hit_wall:
    animate(direction)
def animate(direction):
    if direction == (0, 1):
        /code to make it bounce the opposite direction
    elif direction == (0, -1):
        /code to make it bounce the opposite direction
    elif direction == (1, 0):
        /code to make it bounce the opposite direction
    elif direction == (-1, 0):
        /code to make it bounce the opposite direction

Upvotes: 0

Related Questions