乒乓球比赛的随机方向球

时间:2015-01-24 10:35:29

标签: pygame

我想制作类似Pong的比赛,但我不知道如何让球以随机的角度进行并从墙上反弹。到目前为止,我有这个。这只是一个跟随球的y轴的敌方玩家,它会从玩家和敌人身上反弹。

import pygame,time,pygame.mixer
from pygame.locals import *
from random import randint
pygame.init()
#set screen to be the window 
screen=pygame.display.set_mode((640,480))
#fills screen with white
screen.fill((255,255,255))
#set starting gravity
gravity=0.5
#limits fps
FPS=60
fpstime=pygame.time.Clock()
timer=0
#sets colour codes
red=(255,0,0)
green=(0,255,0)
blue=(0,0,255)
white=(255,255,255)
#set player starting location
playerpos1=10
playerpos2=240
direction=20
#ball starting location
ballpos1=320
ballpos2=240
ballspeed=3
#enemypos
enemypos=ballpos2
#makes the game loop start
FLYING=True
#game loop

while FLYING:
    mx,my = pygame.mouse.get_pos()
    screen.fill((255,255,255))
    #draws the player and ball
    pygame.draw.rect(screen,blue,(playerpos1,my,10,50))
    pygame.draw.rect(screen,red,(ballpos1,ballpos2,20,20))
    pygame.draw.rect(screen,green,(630,ballpos2,10,50))
    #ball speed and random direction
    ballpos1-=ballspeed
    balldirection=randint(60,90)
    #draws collision boxes
    rightside=pygame.Rect(630,0,10,480)
    leftside=pygame.Rect(10,0,10,480)
    top=pygame.Rect(0,0,640,10)
    ball=pygame.Rect(ballpos1,ballpos2,20,20)
    enemy=pygame.Rect((630,ballpos2,10,50))
    player=pygame.Rect(playerpos1,my,20,20)
    #checks for collisions
    if ball.colliderect(player):
        ballspeed=-3
    if ball.colliderect(enemy):
        ballspeed=3




    #checks if you exit
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            break
        if event.type == KEYDOWN:
            if event.key == K_w:
                playerpos2-=2








    pygame.display.update()
    fpstime.tick(FPS)

1 个答案:

答案 0 :(得分:1)

由于乒乓球不需要大角度弹跳,因此可以通过可能的八个方向轻松完成。

side = 'left'
vert = 'up'

if ballX == 'insert collision points with paddles':
     if side == 'left':
        side = 'right'
    else:
        side = 'left'
    if vert == 'up':
        vert = 'down'
    else:
        vert = 'up'

if vert == 'up':
    ballY -=10
else:
    ballY +=10

if side == 'left':
    ballX-=10
else:
    ballx+=10

这将使球始终对角移动,我发现这对于乒乓球来说效果很好。如果你想让图片完美弹跳,请参考本教程

http://www.petercollingridge.co.uk/pygame-physics-simulation