【发布时间】:2021-03-20 12:09:01
【问题描述】:
我试图让一个球推动另一个球,问题是当球相撞时,红球进入蓝色,红色向鼠标左键移动,蓝色球在鼠标右键单击时被绘制。我注意到速度 (Velocidad) 和
self.xb2-=self.dx+overlapx/(tamaño/2)
self.yb2-=self.dy+overlapy/(tamaño/2)
除数 tamaño/2 的大小在问题中具有重要作用。
这是代码
import pygame, math, random
pygame.init()
vel = 5
ancho = 600
alto = 500
tamaño=30
color = (250,0,0)
color2= (0,0,250)
FPS=60
negro= 0,0,0
posantes = [[300,250], [- 50, - 50]] #posicion anterior, bola y bola1/ initial position bola , initial position bola1
mouse = [[300,250], [ - 50, - 50]] #posicion mouse, click izquierdo , click derecho
pantalla = pygame.display.set_mode((ancho, alto))
reloj = pygame.time.Clock()
class Bola():
def __init__(self, color, xyb, tamaño):
super().__init__()
pygame.draw.circle(pantalla, color, xyb,tamaño)
def colision(self,xyb,xyb2):
self.colision = False
self.xyb = posantes [0]
self.xyb2 = posantes[1]
self.xb,self.yb = posantes[0][0],posantes[0][1]
self.xb2,self.yb2 = posantes[1][0],posantes[1][1]
dist = math.hypot(self.xb2-self.xb,self.yb2-self.yb)
if dist<tamaño*2:
self.colision =True
else:
self.colision =False
def reaccion(self,xyb,xyb2):
overlapx , overlapy = self.xb-self.xb2, self.yb-self.yb2
if self.colision==True:
self.xb2-=self.dx+overlapx/(tamaño/2)
self.yb2-=self.dy+overlapy/(tamaño/2)
posantes[1]=[self.xb2,self.yb2]
print(" !! reaccion ¡¡")
def moverbola(self, xyb, xy,bi):
self.xyb = posantes[bi]
self.xy = mouse[bi]
self.xb,self.yb = self.xyb[0] , self.xyb[1]
self.x,self.y = self.xy[0] , self.xy[1]
self.dx,self.dy = abs(self.x-self.xb) , abs(self.y-self.yb)
dist = math.hypot(self.x-self.xb,self.y-self.yb)
if dist!= 0:
self.dx = self.dx / dist
self.dy = self.dy / dist
if self.xb < self.x:
self.xb+=vel * self.dx
if self.xb > self.x:
self.xb-=vel * self.dx
if self.yb < self.y:
self.yb+=vel * self.dy
if self.yb > self.y :
self.yb -=vel * self.dy
self.xyb = [self.xb,self.yb]
posantes[bi] = self.xyb
terminar = False
while not terminar:
reloj.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
terminar=True
if event.type == pygame.MOUSEBUTTONDOWN and event.button==1:
mouse[0] = pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]
if event.type == pygame.MOUSEBUTTONDOWN and event.button==3:
mouse[1] = pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1]
posantes[1] = mouse[1]
pantalla.fill(negro)
bola1 = Bola(color2, posantes[1], tamaño)
bola = Bola(color,posantes[0], tamaño)
bola.moverbola(posantes[0], mouse[0],0)
bola.colision(posantes[0],posantes[1])
bola.reaccion(posantes[0],posantes[1])
pygame.display.update()
pygame.quit()
quit()
【问题讨论】:
标签: python pygame push physics collision