简体   繁体   中英

Pong Game - Ball Collision with Paddles?

Here is my collision code for the ball with the walls - Created in python(Codeskulptor)

The ball bounces off the bottom and top walls, and disappears from the left and right side if it is not hit by the paddle and reappears in the center to repeat

However, I cannot get the ball to hit the paddle and rebound - the paddle is a Circle object placed on the left of the screen (Height/2)

Any help would be appreciated

#Bottom and top walls
if Ballpos[1] >= (Height - Ballradius):
    Ballvel[1] = - Ballvel[1]
if Ballpos[1] <= (Ballradius):
    Ballvel[1] = - Ballvel[1]

if(Ballpos[0] <= 0):
    Score2 += 1
    Ball_Spawn(True)
elif(Ballpos[0] >= Width):
    Score1 += 1
    Ball_Spawn(False) 


#Update Position of Ball
Ballpos[0] += Ballvel[0]
Ballpos[1] += Ballvel[1]

Let's pretend your paddle has coordinates Padpos and radius Padradius . From your code, it looks like the coordinates represent the center of the circle, but you can make necessary adjustments if I'm wrong on that.

if (Ballpos[0] - Padpos[0])**2 + (Ballpos[1] - Padpos[1])**2 <= (Ballradius + Padradius)**2:
    # code for rebounding

Basically, just apply Pythagorean Theorem to see if the distance between their centers is closer than the sum of their radii.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM