I'm trying to make one ball push another, the problem is that when the balls collide the red ball gets into the blue, the red moves towards the left mouse click, the blue one is drawn with the right mouse click. I've noticed that the speed (Velocidad) and
self.xb2-=self.dx+overlapx/(tamaño/2)
self.yb2-=self.dy+overlapy/(tamaño/2)
the magnitude of the divisor, tamaño/2, has a significant role in the problem.
here's the code
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()