【问题标题】:Pygame bouncing bubblesPygame 弹跳泡泡
【发布时间】:2016-03-18 21:20:02
【问题描述】:

我想在 pygame 中制作一种屏幕保护程序,气泡在屏幕内弹跳,同时相互弹跳。我怎样才能做到这一点?下面是在屏幕内弹跳的部分:

import pygame
from pygame.locals import *

WIDTH=1
TV_SIZE=(800,900)

pygame.init()

CLOCK=pygame.time.Clock()
TV=pygame.display.set_mode(TV_SIZE)

class Ball(object):

    def __init__(self,pos_x,x_dir,pos_y,y_dir,color,radius):
        self.pos_x=pos_x
        self.x_dir=x_dir
        self.pos_y=pos_y
        self.y_dir=y_dir
        self.color=color
        self.radius=radius
    def move(self):
        if self.pos_x>=TV_SIZE[0]-self.radius or self.pos_x<=self.radius:
            self.x_dir=-self.x_dir
            self.pos_x+=self.x_dir
        if self.pos_y>=TV_SIZE[1]-self.radius or self.pos_y<=self.radius:
            self.y_dir=-self.y_dir
            self.pos_y+=self.y_dir
        else:
            self.pos_x+=self.x_dir
            self.pos_y+=self.y_dir
            pygame.draw.circle(TV,self.color,(self.pos_x,self.pos_y),self.radius,WIDTH)
            pygame.display.flip()

ball_1=Ball(100,5,100,5,(100,100,100),50)
ball_2=Ball(31,8,31,8,(200,200,100),30)

while True:
    for e in pygame.event.get():
        if e.type==QUIT:
            pygame.quit()

    ball_1.move()
    ball_2.move()
    TV.fill((0,0,0))

    CLOCK.tick(30)

【问题讨论】:

    标签: python python-2.7 pygame


    【解决方案1】:

    这可以工作:

    1. 检查圆心之间的距离。 (如果它小于它们的半径之和,则它正在碰撞)要找到距离,请找到 x 或 y 像素距离。以像素为单位的距离为:

      sqrt((x_dist**2) + (y_dist**2)). 
      

    http://i.stack.imgur.com/EFR8f.png

    1. 如果它们发生碰撞,则开始反弹。然后,你需要物理。请记住:力 = 质量(加速度),总能量 = 势能 + 动能。不过,我真的帮不了你。只需根据它们的碰撞方式更改 x_dir 和 y_dir 即可。实验。

    2. 请随时问我任何问题! =D

    【讨论】:

      猜你喜欢
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      相关资源
      最近更新 更多