【问题标题】:Use vector2 in pygame. Collide with the window frame and restrict the ball to the rectangular area在 pygame 中使用 vector2。与窗框碰撞,将球限制在矩形区域内
【发布时间】:2021-10-16 06:21:21
【问题描述】:

嘿,我正在尝试使用 pygame 创建一个突破性克隆,我使用了

self.course(180 - self.course) % 360

要反弹桨的球,但是我正在研究矢量 2 类,但我不知道如何使用它来转换我的 Ball 类。如果有人能指引我正确的方向。

这是我想使用vector2转换的代码。

import pygame
import math

class Ball(pygame.sprite.Sprite):

    course = 130

    def __init__(self):
        # Calling the parent class (Sprite)
        pygame.sprite.Sprite.__init__(self)

        # Creating the ball and load the ball image
        self.image = pygame.image.load("ball.png").convert()
        self.rect = self.image.get_rect()
        self.rect.x = 0
        self.rect.y = 270

    # Creating a bounce function to make the ball bounce of surfaces.
    def bounce(self, diff):
        self.course = (180 - self.course) % 360
        self.course -= diff
        
    # Create the function that will update the ball.
    def update(self):
        course_radianse = math.radians(self.course)
        self.rect.x += 10 * math.sin(course_radianse)
        self.rect.y -= 10 * math.cos(course_radianse)
        self.rect.x = self.rect.x
        self.rect.y = self.rect.y
        
        # Check if ball goes past top
        if self.rect.y <= 0:
            self.bounce(0)
            self.rect.y = 1
            
        # Check if ball goes past left side
        if self.rect.x <= 0:
            self.course = (360 - self.course) % 360
            self.rect.x = 1
            
        # Check if ball goes past right side
        if self.rect.x >= 800:
            self.course = (360 - self.course) % 360
            self.rect.x = 800 - 1
            
        if self.rect.y > 600:
            return True
        else:
            return False

【问题讨论】:

  • 你究竟想通过使用它来实现什么?
  • 我想避免使用 cos 和 sin,以熟悉在 pygame 中使用 vector2。我相信我需要在使用 vector2 时声明我的所有对象,但我不熟悉该过程。希望这回答了你的问题

标签: python vector pygame collision-detection


【解决方案1】:

向量定义了方向和数量。您必须将矢量添加到球的位置。可悲的是pygame.Rect 只存储整数,因此对象的位置也必须存储在pygame.math.Vector2 中。您需要 1 个向量作为对象的位置,第 2 个向量作为方向。每次位置更改时,.rect 属性必须由舍入位置设置。 如果物体撞击表面,则球会被 Normal vector 反射 (.reflect()) 到表面。

最小示例: repl.it/@Rabbid76/PyGame-BallBounceOffFrame

import pygame
import random

class Ball(pygame.sprite.Sprite):

    def __init__(self, startpos, velocity, startdir):
        super().__init__()
        self.pos = pygame.math.Vector2(startpos)
        self.velocity = velocity
        self.dir = pygame.math.Vector2(startdir).normalize()
        self.image = pygame.image.load("ball.png").convert_alpha()
        self.rect = self.image.get_rect(center = (round(self.pos.x), round(self.pos.y)))

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

    def update(self):
        self.pos += self.dir * self.velocity
        self.rect.center = round(self.pos.x), round(self.pos.y)
   
pygame.init()
window = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()

all_groups = pygame.sprite.Group()
start, velocity, direction = (250, 250), 5, (random.random(), random.random())
ball = Ball(start, velocity, direction)
all_groups.add(ball)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    all_groups.update()

    if ball.rect.left <= 100:
        ball.reflect((1, 0))
    if ball.rect.right >= 400:
        ball.reflect((-1, 0))
    if ball.rect.top <= 100:
        ball.reflect((0, 1))
    if ball.rect.bottom >= 400:
        ball.reflect((0, -1))

    window.fill(0)
    pygame.draw.rect(window, (255, 0, 0), (100, 100, 300, 300), 1)
    all_groups.draw(window)
    pygame.display.flip()

假设您有一组块:

block_group = pygame.sprite.Group()

检测ballblock_group 的冲突。一旦检测到碰撞(pygame.sprite.spritecollide()),reflect 块上的球:

block_hit = pygame.sprite.spritecollide(ball, block_group, False)
if block_hit:
    bl = block_hit[0].rect.left  - ball.rect.width/4
    br = block_hit[0].rect.right + ball.rect.width/4
    nv = (0, 1) if bl < ball.rect.centerx < br else (1, 0)
    ball.reflect(nv)

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多