簡體   English   中英

Pygame 矩形碰撞

[英]Pygame Rect Collision

我正在使用 Python 在 Pygame 中創建 Pong 游戲(顯然)並且我是 Pygame 的新手,所以想要一些幫助來處理球接觸球拍時的物理學,它會反轉速度並朝着相反的方向前進。 到目前為止一切正常,但是當球到達槳時,它會直接穿過它並且不會改變方向。 我已經解決了,所以槳不會離開屏幕,當球碰到牆壁時會改變方向,但當球碰到槳時不會改變方向。 任何幫助或提示將不勝感激。

我的槳類:

class Paddle:    
    def __init__(self, x, y):    
        self.x = x
        self.y = y
        self.height = 40
        self.width = 10

    def draw(self, canvas):
         pygame.draw.rect(canvas, pygame.Color(0,0,255),(self.x,self.y,self.width,self.height))
    def contains(self, ptX, ptY):
        return self.x < ptX < self.x + self.width & self.y < ptY < self.y + self.height
    def overlaps(self, otherRectangle):
        return otherRectangle.colliderect(Rect(self.x,self.y,self.height, self.width))

我的球類

class Ball:
    def __init__(self, x, y):    
        #position of ball
        self.x = x
        self.y = y

        #speed of ball
        self.dx = 5
        self.dy = 5

        self.height = 10
        self.width = 10

    def draw(self, canvas):
        pygame.draw.rect(canvas, pygame.Color(0,255,0), (self.x,self.y,self.width,self.height))

    def reset(self):
        self.x = 320
        self.y = 240

        self.dx = -self.dx
        self.dy = 5

我的目標是讓球在接觸球拍或反彈(重疊點)時的速度反向(負速度)。

您擁有的代碼可能有點過分。 讓我們來點更簡單的事情。 在你的draw函數中(在BallPaddle ),繼續讓你的線條的開始看起來像這樣:

self.rect = pygame.draw.rect...

然后你可以使用colliderect函數:

if ball.rect.colliderect(paddle1):
    # Reverse, reverse!

對於碰撞使用下面的代碼但更改變量

如果paddle1.colliderect(paddle2)或paddle2.colliderect(paddle1):即x軸球方向ballDirectionX*=-1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM