Problem with calculating line intersections - python

I am trying to display the points of intersecting lines, but the calculated points are between the actual intersectings.
(https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection)
I have checked the formulars multiple times and used another formula for calculating the intersecting points x, y [x3+u*(x4-x3), y3+u*(y4-y3)] instead of [x1+t*(x2-x1), y1+t*(y2-y1)], but that just made the points somewhere really wrong
("d" is not referenced on the wikipedia page and is just the divisor for the formulars of t and u)
Function for calculating the intersection
def checkcol(self, startObs, endObs):
x1, y1 = startObs
x2, y2 = endObs
x3, y3 = run.lamp
x4, y4 = self.endpoint
d = (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4)
t = ((x1-x3)*(y3-y4)-(y1-y3)*(x3-x4))/d
u = ((x1-x2)*(y1-y3)-(y1-y2)*(x1-x3))/d
if 0 < t < 1 and 1 > u > 0:
pygame.draw.circle(run.screen, pygame.Color('green'), (round(x1+t*(x2-x1)), round(y1+t*(y2-y1))), 3)
The whole code
import pygame
import sys
import math
import random as rd
class Obs(object):
def __init__(self, startp, endp):
self.startp = startp
self.endp = endp
def drawww(self):
pygame.draw.line(run.screen, pygame.Color('red'), (self.startp), (self.endp))
for ray in run.lines:
ray.checkcol(self.startp, self.endp)
class rays(object):
def __init__(self, endpoint):
self.width = 2
self.endpoint = endpoint
def draww(self):
pygame.draw.line(run.screen, pygame.Color('white'), run.lamp, self.endpoint, 2)
def moveEnd(self, xoff, yoff):
self.endpoint[0] += xoff
self.endpoint[1] += yoff
def checkcol(self, startObs, endObs):
x1, y1 = startObs
x2, y2 = endObs
x3, y3 = run.lamp
x4, y4 = self.endpoint
d = (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4)
t = ((x1-x3)*(y3-y4)-(y1-y3)*(x3-x4))/d
u = ((x1-x2)*(y1-y3)-(y1-y2)*(x1-x3))/d
if 0 < t < 1 and 1 > u > 0:
pygame.draw.circle(run.screen, pygame.Color('green'), (round(x1+t*(x2-x1)), round(y1+t*(y2-y1))), 3)
class Control(object):
def __init__(self):
self.winw = 800
self.winh = 800
self.screen = pygame.display.set_mode((self.winw, self.winh))
self.fps = 60
self.clock = pygame.time.Clock()
self.lamp = [400, 400]
self.lampr = 13
self.lines = []
self.r = 10
self.Obs = [Obs((rd.randint(0, self.winw), rd.randint(0, self.winh)),
(rd.randint(0, self.winw), rd.randint(0, self.winh))) for i in range(5)]
self.done = False
def event_loop(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_F5:
self.__init__()
if pygame.mouse.get_pressed() == (1, 0, 0):
self.lamp = (pygame.mouse.get_pos())
for line in self.lines:
line.moveEnd(pygame.mouse.get_rel()[0], pygame.mouse.get_rel()[1])
def draw(self):
self.screen.fill((pygame.Color('black')))
pygame.draw.circle(self.screen, pygame.Color('white'), self.lamp, self.lampr)
for line in self.lines:
line.draww()
for obs in self.Obs:
obs.drawww()
def createlines(self):
self.lines.clear()
for angle in range(0, 361, 9):
self.lines.append(rays([self.lamp[0] + 1200 * math.cos(angle), self.lamp[1] + 1200 * math.sin(angle)]))
def main_loop(self):
while not self.done:
self.event_loop()
self.createlines()
self.draw()
pygame.display.update()
self.clock.tick(self.fps)
pygame.display.set_caption(f"Draw FPS: {self.clock.get_fps()}")
if __name__ == '__main__':
run = Control()
run.main_loop()
pygame.quit()
sys.exit()
Expected the points of intersecting to be at the actual points of intersection.

To find the intersection points of 2 rays or line segments in two-dimensional space, I use vector arithmetic and the following algorithm:
P ... point on the 1. line
R ... direction of the 1. line
Q ... point on the 2. line
S ... direction of the 2. line
alpha ... angle between Q-P and R
beta ... angle between R and S
gamma = 180° - alpha - beta
h = | Q - P | * sin(alpha)
u = h / sin(beta)
t = | Q - P | * sin(gamma) / sin(beta)
t = dot(Q-P, (S.y, -S.x)) / dot(R, (S.y, -S.x)) = determinant(mat2(Q-P, S)) / determinant(mat2(R, S))
u = dot(Q-P, (R.y, -R.x)) / dot(R, (S.y, -S.x)) = determinant(mat2(Q-P, R)) / determinant(mat2(R, S))
X = P + R * t = Q + S * u
See also Line–line intersection
If t == 1, then X = P + R. This can be used to assess whether the intersection is on a line segment.
If a line is defined through the 2 points L1 and L2, it can be defined that P = L1 and R = L2-L1. Therefore the point of intersection (X) lies on the line segment from L1 to L2 if 0 <= t <= 1.
The same relation applies to u and S.
The following function implements the above algorithm using pygame.math.Vector2 objects of the pygame.math module:
def intersect_line_line_vec2(startObs, endObs, origin, endpoint):
P = pygame.Vector2(startObs)
R = (endObs - P)
Q = pygame.Vector2(origin)
S = (endpoint - Q)
d = R.dot((S.y, -S.x))
if d == 0:
return None
t = (Q-P).dot((S.y, -S.x)) / d
u = (Q-P).dot((R.y, -R.x)) / d
if 0 <= t <= 1 and 0 <= u <= 1:
X = P + R * t
return (X.x, X.y)
return None
The same algorithm without the use of the pygame.math module, less readable but more or less the same:
def intersect_line_line(P0, P1, Q0, Q1):
d = (P1[0]-P0[0]) * (Q1[1]-Q0[1]) + (P1[1]-P0[1]) * (Q0[0]-Q1[0])
if d == 0:
return None
t = ((Q0[0]-P0[0]) * (Q1[1]-Q0[1]) + (Q0[1]-P0[1]) * (Q0[0]-Q1[0])) / d
u = ((Q0[0]-P0[0]) * (P1[1]-P0[1]) + (Q0[1]-P0[1]) * (P0[0]-P1[0])) / d
if 0 <= t <= 1 and 0 <= u <= 1:
return P1[0] * t + P0[0] * (1-t), P1[1] * t + P0[1] * (1-t)
return None
Applied to your code, this means:
class rays(object):
# [...]
def checkcol(self, startObs, endObs):
P = pygame.Vector2(startObs)
R = (endObs - P).normalize()
Q = pygame.Vector2(run.lamp)
S = (self.endpoint - Q).normalize()
d = R.dot((S.y, -S.x))
if R.dot((S.y, -S.x)) == 0:
return
t = (Q-P).dot((S.y, -S.x)) / d
u = (Q-P).dot((R.y, -R.x)) / d
if 0 <= t <= 1 and 0 <= u <= 1:
X = P + R * t
pygame.draw.circle(run.screen, pygame.Color('green'), (round(X.x), round(X.y)), 3)
Minimal example: repl.it/#Rabbid76/PyGame-IntersectLines
import pygame
import math
import random
def intersect_line_line_vec2(startObs, endObs, origin, endpoint):
P = pygame.Vector2(startObs)
R = (endObs - P)
Q = pygame.Vector2(origin)
S = (endpoint - Q)
d = R.dot((S.y, -S.x))
if d == 0:
return None
t = (Q-P).dot((S.y, -S.x)) / d
u = (Q-P).dot((R.y, -R.x)) / d
if 0 <= t <= 1 and 0 <= u <= 1:
X = P + R * t
return (X.x, X.y)
return None
def intersect_line_line(P0, P1, Q0, Q1):
d = (P1[0]-P0[0]) * (Q1[1]-Q0[1]) + (P1[1]-P0[1]) * (Q0[0]-Q1[0])
if d == 0:
return None
t = ((Q0[0]-P0[0]) * (Q1[1]-Q0[1]) + (Q0[1]-P0[1]) * (Q0[0]-Q1[0])) / d
u = ((Q0[0]-P0[0]) * (P1[1]-P0[1]) + (Q0[1]-P0[1]) * (P0[0]-P1[0])) / d
if 0 <= t <= 1 and 0 <= u <= 1:
return P1[0] * t + P0[0] * (1-t), P1[1] * t + P0[1] * (1-t)
return None
def createRays(center):
return [(center[0] + 1200 * math.cos(angle), center[1] + 1200 * math.sin(angle)) for angle in range(0, 360, 10)]
def createObstacles(surface):
w, h = surface.get_size()
return [((random.randrange(w), random.randrange(h)), (random.randrange(w), random.randrange(h))) for _ in range(5)]
window = pygame.display.set_mode((800, 800))
clock = pygame.time.Clock()
origin = window.get_rect().center
rays = createRays(origin)
obstacles = createObstacles(window)
move_center = True
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
obstacles = createObstacles(window)
if event.type == pygame.KEYDOWN:
move_center = not move_center
if move_center:
origin = pygame.mouse.get_pos()
rays = createRays(origin)
window.fill(0)
for endpoint in rays:
pygame.draw.line(window, (128, 128, 128), origin, endpoint)
pygame.draw.circle(window, (255, 255, 255), origin, 10)
for start, end in obstacles:
pygame.draw.line(window, (255, 0, 0), start, end)
for endpoint in rays:
pos = intersect_line_line(start, end, origin, endpoint)
if pos:
pygame.draw.circle(window, (0, 255, 0), (round(pos[0]), round(pos[1])), 3)
pygame.display.flip()
pygame.quit()
exit()

Related

Trouble creating a line perpendicular to player -> cursor line

I am trying raycasting methods and want to simply draw a triangle in the direction of my cursor, with that triangle having a 90 degree angle at the cursor, so that it is a right angle triangle.
I am currently using solely the player's coordinates and the mouse's coordenates to calculate a coordinate of the point of the triangle. I use pygame to draw the lines and create this app.
Here is my existing python code :
import pygame as pg, sys, time, math, numpy as np
class RayCast:
def calc_bearing(
self, charX, charY, charW, charH
): # take position of character and mouse, calculate distance using pythagoras and then angle using sohcahtoa -> "toa" tan-1(change in y , change in x)
mouseX, mouseY = pg.mouse.get_pos()
charX = charX + charW // 2
charY = charY + charH // 2
deltaY = charY - mouseY
deltaX = -1 * (charX - mouseX)
distance = math.sqrt(((deltaY**2) + (deltaX**2)))
#print(f"{deltaX} <-- DeltaX | DeltaY --> {deltaY}")
if deltaY != 0:
ANGLE = abs(math.degrees(math.atan(deltaX / deltaY)))
if deltaY < 0 and deltaX > 0:
ANGLE = 180 - ANGLE
elif deltaX == 0 and deltaY < 0:
ANGLE = 180
elif deltaY < 0 and deltaX < 0:
ANGLE += 180
elif deltaY > 0 and deltaX < 0:`your text`
ANGLE = 360 - ANGLE
else:
if deltaX > 0:
ANGLE = 90
elif deltaX < 0:
ANGLE = 270
#print(
# ANGLE
#) # PROBLEM, if both are negative, then angle is positive and vice versa // SOLVED
# finds bearing of mouse relative to player - works
class Game(RayCast):
def __init__(self):
pg.init()
#clock = pg.time.Clock()
self.WIDTH, self.HEIGHT = 800, 800
self.charWidth, self.charHeight = 50, 50
self.character = pg.Rect(
(self.WIDTH // 2 - self.charWidth // 2),
(self.HEIGHT // 2 - self.charHeight // 2), self.charWidth,
self.charHeight) # left,top,width,height , start in center
self.WIN = pg.display.set_mode((self.WIDTH, self.HEIGHT))
pg.display.set_caption("Ray Cast")
self.start_time = time.time()
self.raycast = RayCast()
self.WHITE = (255, 255, 255)
while True:
self.mainLoop()
def mainLoop(self):
self.updateScreen()
self.handleMove()
self.raycast.calc_bearing(self.character.x, self.character.y,
self.charWidth, self.charHeight)
self.deltaTime = self.calcDeltaTime(
self.start_time) #calc delta time (change in time)
self.start_time = self.calcFPS(self.start_time)
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit(0)
def calcFPS(self, start):
if time.time() - start != 0:
fps = 1 / (time.time() - start)
#print(f"FPS --> {fps}")
return time.time()
def updateScreen(self):
self.WIN.fill((0, 0, 0))
pg.draw.rect(self.WIN, self.WHITE, self.character)
self.draw_line()
self.draw_triangle()
pg.display.update()
def handleMove(self):
keys = pg.key.get_pressed()
if keys[pg.K_w]:
self.character.y -= 0.75 * self.deltaTime
if keys[pg.K_a]:
self.character.x -= 0.75 * self.deltaTime
if keys[pg.K_s]:
self.character.y += 1 * self.deltaTime
if keys[pg.K_d]:
self.character.x += 1 * self.deltaTime
def calcDeltaTime(self, start):
#print(f"DeltaTime --> {(time.time() - start) + 1}")
return ((time.time() - start) + 1)
def draw_line(self):
point1 = tuple([
self.character.x + self.charWidth // 2,
self.character.y + self.charHeight // 2
])
point2 = pg.mouse.get_pos()
#print(f"{point1} <-- POINT1 | POINT2 --> {point2}")
# surface, colour, start, end, width
pg.draw.line(self.WIN, self.WHITE, point1, point2, width=2)
def draw_triangle(self):
charX, charY = self.character.x + self.charWidth//2, self.character.y + self.charHeight//2
mouseX, mouseY = pg.mouse.get_pos()
deltax = abs(mouseX) - abs(charX)
deltay = abs(mouseY) - abs(charY)
if (deltax!= 0) and (deltay != 0):
# sqrt((sqrt(x1^2 + y1^2)^2) + 100^2) * (sin((sin-1(100/ sqrt(x1^2 + y1^2)^2 + 100^2))) + (180 - (tan-1(x/y)) - 90))
r = math.sqrt(math.sqrt((deltax**2) + (deltay**2))+100**2)
theta1 = np.arcsin((100/r))
z = (np.arctan(deltax / deltay))
theta2 = 90 - z
o = r * (np.sin(theta1 + theta2))
a = r * (np.cos(theta1 + theta2))
point1 = (mouseX + o, mouseY + a)
playerPos = (charX,charY)
pg.draw.line(self.WIN, self.WHITE, point1, pg.mouse.get_pos(), width=2)
pg.draw.line(self.WIN, self.WHITE, point1,playerPos, width = 2 )
#r2 = np.sqrt((deltax**2 + deltay**2))
# r1 = np.sqrt(r2**2 + 100**2)
#theta2 = math.degrees(np.arccos(deltax / r2)) # in radians
#theta1 = math.degrees(np.arccos(r2/r1)) # in radians
#o = r1 * np.sin(theta1 + theta2)
#a = r1 * np.cos(theta1 + theta2)
#point1 = (mouseX + o, mouseY + a)
#pg.draw.line(self.WIN, self.WHITE, point1, pg.mouse.get_pos(), width = 2 )
else:
if (charX - mouseX == 0 and mouseY > charY): # is below the player
pass
elif (charX - mouseX == 0) and (mouseY < charY): # above player
pass
elif (charY - mouseY == 0): # left of player
#pg.draw.line(self.WIN, self.WHITE,
# (self.character.x, self.character.y - oppLength // 2),
# (self.character.x, self.character.y + oppLength // 2))
pass
elif (charY - mouseY == 0): # right of player
#pg.draw.line(self.WIN, self.WHITE,
# (self.character.x, self.character.y - oppLength // 2),
# (self.character.x, self.character.y + oppLength // 2))
pass
#print(m)
game = Game()
the error is in the draw_triangle() function. Please help me figure this out.
I tried a few different equations but the one I decided to use was :
a = sqrt((sqrt(x1^2 + y1^2)^2) + 100^2) * (sin((sin-1(100/ sqrt(x1^2 + y1^2)^2 + 100^2))) + (180 - (tan-1(x/y)) - 90))
pg.drawline(self.WIN,self.WHITE,(playerposX + a, playerposY), mousePos, width = 2)
but this draws a line in the complete wrong place.

Trajectory plalnification

I have a program that generates circles and lines, where the circles can not collide with each other and the lines can not collide with the circles, the problem is that it only draws a line but not the others, it does not mark any error and as much as I think the reason I do not understand why, (I'm new to python, so excuse me if maybe the error is obvious)
I tried to remove the for from my CreaLin class and it does generate the lines but they all collide with the circles, I also thought that the collisionL function could be the problem since the method does not belong as such to the line class, but I need values from the circle class, so I don't know what would be another way to do it, I would like to know a method.
my code:
class CreaCir:
def __init__(self, figs):
self.figs = figs
def update(self):
if len(self.figs) <70:
choca = False
r = randint(5, 104)
x = randint(0, 600 + r)
y = randint(0, 400 + r)
creOne = Circulo(x, y, r)
for fig in (self.figs):
choca = creOne.colisionC(fig)
if choca == True:
break
if choca == False:
self.figs.append(creOne)
def dibujar(self, ventana):
pass
class CreaLin:
def __init__(self, lins):
self.lins = lins
def update(self):
if len(self.lins) <70:
choca = False
x = randint(0, 700)
y = randint(0, 500)
a = randint(0, 700)
b = randint(0, 500)
linOne = Linea(x, y, a, b)
for lin in (self.lins):
choca = linOne.colisionL(lin)
if choca == True:
break
if choca == False:
self.lins.append(linOne)
def dibujar(self, ventana):
pass
class Ventana:
def __init__(self, Ven_Tam= (700, 500)):
pg.init()
self.ven_tam = Ven_Tam
self.ven = pg.display.set_caption("Linea")
self.ven = pg.display.set_mode(self.ven_tam)
self.ven.fill(pg.Color('#404040'))
self.figs = []
self.lins = []
self.reloj = pg.time.Clock()
def check_events(self):
for event in pg.event.get():
if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):
quit()
pg.display.flip()
def run(self):
cirCreater = CreaCir(self.figs)
linCreater = CreaLin(self.lins)
while True:
self.check_events()
cirCreater.update()
linCreater.update()
for fig in self.figs:
fig.dibujar(self.ven)
for lin in self.lins:
lin.dibujar(self.ven)
self.reloj.tick(60)
if __name__ == '__main__':
ven = Ventana()
ven.run()
class Circulo:
class Circulo(PosGeo):
def __init__(self, x, y, r):
self.x = x
self.y = y
self.radio = r
self.cx = x+r
self.cy = y+r
def __str__(self):
return f"Circulo, (X: {self.x}, Y: {self.y}), radio: {self.radio}"
def dibujar(self, ventana):
pg.draw.circle(ventana, "white", (self.cx, self.cy), self.radio, 1)
pg.draw.line(ventana, "white", (self.cx+2, self.cy+2),(self.cx-2, self.cy-2))
pg.draw.line(ventana, "white", (self.cx-2, self.cy+2),(self.cx+2, self.cy-2))
def update(self):
pass
def colisionC(self, c2):
return self.radio + c2.radio > sqrt(pow(self.cx - c2.cx, 2) + pow(self.cy - c2.cy, 2))
def colisionL(self, L2):
l0 = [L2.x, L2.y]
l1 = [L2.a, L2.b]
cp = [self.cx, self.cy]
x1 = l0[0] - cp[0]
y1 = l0[1] - cp[1]
x2 = l1[0] - cp[0]
y2 = l1[1] - cp[1]
dx = x2 - x1
dy = y2 - y1
dr = sqrt(dx*dx + dy*dy)
D = x1 * y2 - x2 * y1
discriminant = self.radio*self.radio*dr*dr - D*D
if discriminant < 0:
return False
else:
return True`
and finally my class line:
class Linea(PosGeo):
def __init__(self, x, y, a, b):
super().__init__(x, y)
self.x = x
self.y = y
self.a = a
self.b = b
def dibujar(self, ventana):
pg.draw.line(ventana, "#7B0000", (self.x, self.y), (self.a, self.b))
def update(self):
pass
def colisionL(self, l1):
pass
Result:
You need to implement the colisionC and colisionL methods in Linea and Circulo. See Problem with calculating line intersections for the line-line intersection algorithm. When checking for collisions between lines and circles, in addition to checking for collisions between circles and endless lines, you must also consider the beginning and end of the line segment:
class Linea:
# [...]
def colisionC(self, c2):
return c2.colisionL(self)
def colisionL(self, l1):
return Linea.intersect_line_line((self.x, self.y), (self.a, self.b), (l1.x, l1.y), (l1.a, l1.b))
def intersect_line_line(P0, P1, Q0, Q1):
d = (P1[0]-P0[0]) * (Q1[1]-Q0[1]) + (P1[1]-P0[1]) * (Q0[0]-Q1[0])
if d == 0:
return None
t = ((Q0[0]-P0[0]) * (Q1[1]-Q0[1]) + (Q0[1]-P0[1]) * (Q0[0]-Q1[0])) / d
u = ((Q0[0]-P0[0]) * (P1[1]-P0[1]) + (Q0[1]-P0[1]) * (P0[0]-P1[0])) / d
if 0 <= t <= 1 and 0 <= u <= 1:
return P1[0] * t + P0[0] * (1-t), P1[1] * t + P0[1] * (1-t)
return None
class Circulo
# [...]
def colisionC(self, c2):
return self.radio + c2.radio > sqrt(pow(self.cx - c2.cx, 2) + pow(self.cy - c2.cy, 2))
def colisionL(self, L2):
l0 = [L2.x, L2.y]
l1 = [L2.a, L2.b]
cp = [self.cx, self.cy]
x1 = l0[0] - cp[0]
y1 = l0[1] - cp[1]
x2 = l1[0] - cp[0]
y2 = l1[1] - cp[1]
if sqrt(x1*x1+y1*y1) < self.radio or sqrt(x2*x2+y2*y2) < self.radio:
return True
dx = x2 - x1
dy = y2 - y1
dr = sqrt(dx*dx + dy*dy)
D = x1 * y2 - x2 * y1
discriminant = self.radio*self.radio*dr*dr - D*D
if discriminant < 0:
return False
sign = lambda x: -1 if x < 0 else 1
xa = (D * dy + sign(dy) * dx * sqrt(discriminant)) / (dr * dr)
xb = (D * dy - sign(dy) * dx * sqrt(discriminant)) / (dr * dr)
ya = (-D * dx + abs(dy) * sqrt(discriminant)) / (dr * dr)
yb = (-D * dx - abs(dy) * sqrt(discriminant)) / (dr * dr)
ta = (xa-x1)*dx/dr + (ya-y1)*dy/dr
tb = (xb-x1)*dx/dr + (yb-y1)*dy/dr
return 0 < ta < dr or 0 < tb < dr
Put all objects into one container. Before you add a new Linea you have to check if the new "Line" intersects another object with "ColisionL". Before you add a new Circulo, you must check if the new "Line" intersects another object with CollisionC:
class CreaObjects:
def __init__(self, figs):
self.figs = figs
self.no_lines = 0
self.no_circles = 0
def update(self):
if self.no_circles <70:
r = randint(5, 104)
creOne = Circulo(randint(0, 600 - 2*r), randint(0, 400 - 2*r), r)
if not any(fig.colisionC(creOne) for fig in self.figs):
self.figs.append(creOne)
self.no_circles += 1
if self.no_lines <70:
linOne = Linea(randint(0, 700), randint(0, 500), randint(0, 700), randint(0, 500))
if not any(fig.colisionL(linOne) for fig in self.figs):
self.figs.append(linOne)
self.no_lines += 1
Complete example:
import pygame as pg
from random import randint
from math import sqrt, hypot
class Linea:
def __init__(self, x, y, a, b):
self.x = x
self.y = y
self.a = a
self.b = b
def dibujar(self, ventana):
pg.draw.line(ventana, "#7B0000", (self.x, self.y), (self.a, self.b))
def update(self):
pass
def colisionC(self, c2):
return c2.colisionL(self)
def colisionL(self, l1):
return Linea.intersect_line_line((self.x, self.y), (self.a, self.b), (l1.x, l1.y), (l1.a, l1.b))
def intersect_line_line(P0, P1, Q0, Q1):
d = (P1[0]-P0[0]) * (Q1[1]-Q0[1]) + (P1[1]-P0[1]) * (Q0[0]-Q1[0])
if d == 0:
return None
t = ((Q0[0]-P0[0]) * (Q1[1]-Q0[1]) + (Q0[1]-P0[1]) * (Q0[0]-Q1[0])) / d
u = ((Q0[0]-P0[0]) * (P1[1]-P0[1]) + (Q0[1]-P0[1]) * (P0[0]-P1[0])) / d
if 0 <= t <= 1 and 0 <= u <= 1:
return P1[0] * t + P0[0] * (1-t), P1[1] * t + P0[1] * (1-t)
return None
class Circulo:
def __init__(self, x, y, r):
self.x = x
self.y = y
self.radio = r
self.cx = x+r
self.cy = y+r
def __str__(self):
return f"Circulo, (X: {self.x}, Y: {self.y}), radio: {self.radio}"
def dibujar(self, ventana):
pg.draw.circle(ventana, "white", (self.cx, self.cy), self.radio, 1)
pg.draw.line(ventana, "white", (self.cx+2, self.cy+2),(self.cx-2, self.cy-2))
pg.draw.line(ventana, "white", (self.cx-2, self.cy+2),(self.cx+2, self.cy-2))
def update(self):
pass
def colisionC(self, c2):
return self.radio + c2.radio > sqrt(pow(self.cx - c2.cx, 2) + pow(self.cy - c2.cy, 2))
def colisionL(self, L2):
l0 = [L2.x, L2.y]
l1 = [L2.a, L2.b]
cp = [self.cx, self.cy]
x1 = l0[0] - cp[0]
y1 = l0[1] - cp[1]
x2 = l1[0] - cp[0]
y2 = l1[1] - cp[1]
if sqrt(x1*x1+y1*y1) < self.radio or sqrt(x2*x2+y2*y2) < self.radio:
return True
dx = x2 - x1
dy = y2 - y1
dr = sqrt(dx*dx + dy*dy)
D = x1 * y2 - x2 * y1
discriminant = self.radio*self.radio*dr*dr - D*D
if discriminant < 0:
return False
sign = lambda x: -1 if x < 0 else 1
xa = (D * dy + sign(dy) * dx * sqrt(discriminant)) / (dr * dr)
xb = (D * dy - sign(dy) * dx * sqrt(discriminant)) / (dr * dr)
ya = (-D * dx + abs(dy) * sqrt(discriminant)) / (dr * dr)
yb = (-D * dx - abs(dy) * sqrt(discriminant)) / (dr * dr)
ta = (xa-x1)*dx/dr + (ya-y1)*dy/dr
tb = (xb-x1)*dx/dr + (yb-y1)*dy/dr
return 0 < ta < dr or 0 < tb < dr
class CreaObjects:
def __init__(self, figs):
self.figs = figs
self.no_lines = 0
self.no_circles = 0
def update(self):
if self.no_circles <70:
r = randint(5, 104)
creOne = Circulo(randint(0, 600 - 2*r), randint(0, 400 - 2*r), r)
if not any(fig.colisionC(creOne) for fig in self.figs):
self.figs.append(creOne)
self.no_circles += 1
if self.no_lines <70:
linOne = Linea(randint(0, 700), randint(0, 500), randint(0, 700), randint(0, 500))
if not any(fig.colisionL(linOne) for fig in self.figs):
self.figs.append(linOne)
self.no_lines += 1
class Ventana:
def __init__(self, Ven_Tam= (700, 500)):
pg.init()
self.ven_tam = Ven_Tam
self.ven = pg.display.set_caption("Linea")
self.ven = pg.display.set_mode(self.ven_tam)
self.figs = []
self.reloj = pg.time.Clock()
def check_events(self):
for event in pg.event.get():
if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):
quit()
def run(self):
cirCreater = CreaObjects(self.figs)
while True:
self.check_events()
cirCreater.update()
self.ven.fill(pg.Color('#404040'))
for fig in self.figs:
fig.dibujar(self.ven)
pg.display.flip()
self.reloj.tick(60)
if __name__ == '__main__':
ven = Ventana()
ven.run()

Coulombs Law: Protons atract each other

I'am working on a simulation of the Coulomb's Law with pygame, but I have a problem. When I start the Simulation an set two Protons, they attract each other. But there is more!
When I set an electron and a proton, they both start to "travel" with a constant distance to each other in the same direction.
Here is my code:
import pygame
import numpy as np
import math
pygame.init()
# window-settings
WIDTH, HEIGHT = 800, 800
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Electric field simulation")
# constants
Pi = np.pi
epsilon0 = 8.85 * (10**(-12))
q = 1.6 * (10**-19)
# colors
WHITE = (255,255,255)
BLACK = (0,0,0)
BLUE = (100, 149, 237)
RED = (188, 39, 50)
class Charge:
TIMESTEP = 50000
def __init__(self, x, y, radius, color, q):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.q = q
self.x_vel = 0
self.y_vel = 0
def draw(self, win):
pygame.draw.circle(win, self.color, (self.x, self.y), self.radius)
def attraction(self, other):
other_x, other_y = other.x, other.y
distance_x = other_x - self.x
distance_y = other_y - self.y
distance = math.sqrt(distance_x ** 2 + distance_y ** 2)
force = (1 / (4 * Pi * epsilon0)) * self.q * other.q / (distance ** 2)
theta = math.atan2(distance_y, distance_x)
force_x = math.cos(theta) * force
force_y = math.sin(theta) * force
return force_x, force_y
def update_position(self, charges):
total_fx = total_fy = 0
for charge in charges:
if self == charge:
continue
fx, fy = self.attraction(charge)
total_fx += fx
total_fy += fy
self.x_vel += total_fx / self.q * self.TIMESTEP
self.y_vel += total_fy / self.q * self.TIMESTEP
self.x += self.x_vel * self.TIMESTEP
self.y += self.y_vel * self.TIMESTEP
def main():
run = True
clock = pygame.time.Clock()
proton = Charge(200, 200, 10, RED, q)
electron = Charge(300, 200, 10, BLUE, -q)
charges = [electron, proton]
while run:
clock.tick(60)
WIN.fill(WHITE)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN: # To set charges
if event.button == 1: # Sets positive charge
charges.append(Charge(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1], 10, RED, q))
if event.button == 3: # Sets negitive charge
charges.append(Charge(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1], 10, BLUE, -q))
for charge in charges:
charge.update_position(charges)
charge.draw(WIN)
pygame.display.update()
pygame.quit()
if __name__ == "__main__":
main()
I think the problem is the attraction-function, but I don't know how to solve it.
At the moment I have not the possibility to run your code but have you mixed up the direction of your force?
At least Wikipedia calculates r1-r2
Annother source of error might be the sin, cos etc. functions have you checked for your example that the calculated values are correct?
If I understand your code correct you update all positions one after eachother and apply the changes right away. Dependend on your application you might want to
Calculate all forces
Update all Values
Otherwise you have a multiple states of your system in just one time step.
Okay I solved the problem by calculating the direction of the force. With this I calculate at first the the force but return the absolute and then calculate the direction and speed.
Here is the code of my changes (I just changed something in the updating and attracting function):
def attraction(self, other):
other_x, other_y = other.x, other.y
distance_x = self.x - other_x
distance_y = self.y - other_y
distance = math.sqrt(distance_x ** 2 + distance_y ** 2)
if self.q != other.q and distance < 5:
return 0,0
force = (1 / (4 * Pi * epsilon0)) * self.q * other.q / (distance ** 2)
force_x = distance_x / distance*np.abs(force)
force_y = distance_y / distance*np.abs(force)
return force_x, force_y
def update_position(self, charges):
total_fx = total_fy = 0
for charge in charges:
if self == charge:
continue
fx, fy = self.attraction(charge)
total_fx += fx
total_fy += fy
self.x_vel += total_fx / self.q * self.TIMESTEP
self.y_vel += total_fy / self.q * self.TIMESTEP
if self != charge and self.q < 0 and self.q != charge.q:
x = abs(self.x - charge.x)
y = abs(self.y - charge.y)
self.direction = [x / np.sqrt((x ** 2) + (y ** 2)),y / np.sqrt((x ** 2) + (y ** 2))]
elif self != charge and self.q > 0 and self.q != charge.q:
x = abs(self.x - charge.x)
y = abs(self.y - charge.y)
self.direction = [-x / np.sqrt((x ** 2) + (y ** 2)), -y / np.sqrt((x ** 2) + (y ** 2))]
elif self != charge and self.q < 0 and self.q == charge.q:
x = abs(self.x - charge.x)
y = abs(self.y - charge.y)
self.direction = [-x / np.sqrt((x ** 2) + (y ** 2)), -y / np.sqrt((x ** 2) + (y ** 2))]
elif self != charge and self.q > 0 and self.q == charge.q:
x = abs(self.x - charge.x)
y = abs(self.y - charge.y)
self.direction = [x / np.sqrt((x ** 2) + (y ** 2)), y / np.sqrt((x ** 2) + (y ** 2))]
self.x += self.x_vel * self.TIMESTEP * self.direction[0]
self.y += self.y_vel * self.TIMESTEP * self.direction[1]
I know this code isn't that beautiful, but at first it works.

Why 2d raytracing + mirrors do (sometimes) semi transparent mirror (the light goes throught and reflect) [duplicate]

The rays keep casting on the wrong "wall", but only if the lamp is more in the bottom right. If the lamp is in the left up corner everything is working fine.
I have tried a lot of things, but last time I had a problem I wrote I checked the formulars many times and in the end it was a problem with the formular so I am not even gonne try
(https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection)
function for finding the closest wall:
def draw(self):
bestdist = 1000000000000000000
for obs in run.Obs:
x1, y1 = obs.startp
x2, y2 = obs.endp
x3, y3 = run.lamp
x4, y4 = self.maxendpoint
d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if d != 0:
t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / d
u = ((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / d
if 0 < t < 1 and u > 0:
px = round(x1 + t * (x2 - x1))
py = round(y1 + t * (y2 - y1))
dist = px**2+py**2
if dist < bestdist:
bestdist = dist
self.endpoint= [px, py]
# pygame.draw.circle(run.screen, pygame.Color('green'), (px, py), 3)
if len(self.endpoint) == 2:
pygame.draw.line(run.screen, pygame.Color('white'), run.lamp, self.endpoint)
the whole code:
import pygame
import sys
import math
import random as rd
import numpy as np
class Obs(object):
def __init__(self, startp, endp):
self.startp = startp
self.endp = endp
def drawww(self):
pygame.draw.line(run.screen, pygame.Color('red'), (self.startp), (self.endp))
class rays(object):
def __init__(self, maxendpoint):
self.maxendpoint = maxendpoint
self.endpoint = []
def draw(self):
bestdist = 1000000000000000000
for obs in run.Obs:
x1, y1 = obs.startp
x2, y2 = obs.endp
x3, y3 = run.lamp
x4, y4 = self.maxendpoint
d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if d != 0:
t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / d
u = ((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / d
if 0 < t < 1 and u > 0:
px = round(x1 + t * (x2 - x1))
py = round(y1 + t * (y2 - y1))
dist = px**2+py**2
if dist < bestdist:
bestdist = dist
self.endpoint= [px, py]
# pygame.draw.circle(run.screen, pygame.Color('green'), (px, py), 3)
if len(self.endpoint) == 2:
pygame.draw.line(run.screen, pygame.Color('white'), run.lamp, self.endpoint)
class Control(object):
def __init__(self):
self.winw = 800
self.winh = 800
self.screen = pygame.display.set_mode((self.winw, self.winh))
self.fps = 60
self.clock = pygame.time.Clock()
self.lamp = [round(self.winw/2), round(self.winh/2)]
self.lampr = 13
self.lines = []
self.r = 5
self.Obs = []
self.angel = 0
self.fov = 360
self.scene = np.ones(self.fov)
self.done = False
self.makeobs()
def event_loop(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_F5:
self.__init__()
elif event.key == pygame.K_LEFT:
if self.angel <= 0:
self.angel = 360
else:
self.angel -= 5
elif event.key == pygame.K_RIGHT:
if self.angel >= 360:
self.angel = 0
else:
self.angel += 5
elif event.key == pygame.K_w:
self.lamp[1] -= 10
elif event.key == pygame.K_a:
self.lamp[0] -= 10
elif event.key == pygame.K_s:
self.lamp[1] += 10
elif event.key == pygame.K_d:
self.lamp[0] += 10
elif event.key == pygame.K_y:
pass
if pygame.mouse.get_pressed() == (1, 0, 0):
if pygame.mouse.get_pos()[0] > 800:
self.lamp = [799, pygame.mouse.get_pos()[1]]
else:
self.lamp[0] = pygame.mouse.get_pos()[0]
self.lamp[1] = pygame.mouse.get_pos()[1]
def draw(self):
self.screen.fill((pygame.Color('black')))
pygame.draw.circle(self.screen, pygame.Color('white'), self.lamp, self.lampr)
for obs in self.Obs:
obs.drawww()
for line in self.lines:
line.draw()
def makeobs(self):
for i in range(2):
self.Obs.append(Obs((rd.randint(0, self.winw), rd.randint(0, self.winh)),
(rd.randint(0, self.winw), rd.randint(0, self.winh))))
# self.Obs.append(Obs((0, 0), (self.winw, 0)))
# self.Obs.append(Obs((0, 0), (0, self.winh)))
# self.Obs.append(Obs((self.winw, 0), (self.winw, self.winh)))
# self.Obs.append(Obs((0, self.winh), (self.winw, self.winh)))
def createlines(self):
self.lines.clear()
for angle in range(self.angel, self.angel+self.fov):
angle = math.radians(angle)
self.lines.append(rays([self.lamp[0] + math.cos(angle), self.lamp[1] + math.sin(angle)]))
def main_loop(self):
while not self.done:
self.event_loop()
self.createlines()
self.draw()
pygame.display.update()
self.clock.tick(self.fps)
pygame.display.set_caption(f"Draw FPS: {self.clock.get_fps()}")
if __name__ == '__main__':
run = Control()
run.main_loop()
pygame.quit()
sys.exit()
Expected it to work no matter where the lamp is.
The code
px = round(x1 + t * (x2 - x1))
py = round(y1 + t * (y2 - y1))
dist = px**2+py**2
doesn't make any sense, because (py, py) is a point, and so dist = px**2+py**2 is the squared Euclidean distance from the origin (0, 0) to (py, py).
You've to calculate the distance from (x3, x4) to the intersection point:
vx = u * (x4 - x3)
vy = u * (y4 - y3)
dist = vx**2+vy**2
Further there is an issue when in the calculation of u:
u = ((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / d
u = ((x1 - x3) * (y1 - y2) - (y1 - y3) * (x1 - x2)) / d
Method class rays:
class rays(object):
def __init__(self, maxendpoint):
self.maxendpoint = maxendpoint
self.endpoint = []
def draw(self):
bestdist = 1000000000000000000
for obs in run.Obs:
x1, y1 = obs.startp
x2, y2 = obs.endp
x3, y3 = run.lamp
x4, y4 = self.maxendpoint
d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if d != 0:
t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / d
u = ((x1 - x3) * (y1 - y2) - (y1 - y3) * (x1 - x2)) / d
if 0 < t < 1 and u > 0:
vx = u * (x4 - x3)
vy = u * (y4 - y3)
dist = vx**2+vy**2
if dist < bestdist:
px = round(x3 + u * (x4 - x3))
py = round(y3 + u * (y4 - y3))
bestdist = dist
self.endpoint= [px, py]
# pygame.draw.circle(run.screen, pygame.Color('green'), (px, py), 3)
if len(self.endpoint) == 2:
pygame.draw.line(run.screen, pygame.Color('white'), run.lamp, self.endpoint)
Minimal example: repl.it/#Rabbid76/PyGame-IntersectAndCutLines
import pygame
import math
import random
def intersect(obstacles, P0, P1):
bestdist = 1000000000000000000
endpoint = P1
for Q0, Q1 in obstacles:
d = (P1[0]-P0[0]) * (Q1[1]-Q0[1]) + (P1[1]-P0[1]) * (Q0[0]-Q1[0])
if d != 0:
t = ((Q0[0]-P0[0]) * (Q1[1]-Q0[1]) + (Q0[1]-P0[1]) * (Q0[0]-Q1[0])) / d
u = ((Q0[0]-P0[0]) * (P1[1]-P0[1]) + (Q0[1]-P0[1]) * (P0[0]-P1[0])) / d
if 0 <= t <= 1 and 0 <= u <= 1:
vx, vy = (P1[0]-P0[0]) * t, (P1[1]-P0[1]) * t
dist = vx*vx + vy*vy
if dist < bestdist:
px, py = round(Q1[0] * u + Q0[0] * (1-u)), round(Q1[1] * u + Q0[1] * (1-u))
bestdist = dist
endpoint = (px, py)
return endpoint
def createRays(center):
return [(center[0] + 1200 * math.cos(angle), center[1] + 1200 * math.sin(angle)) for angle in range(0, 360, 10)]
def createObstacles(surface):
w, h = surface.get_size()
return [((random.randrange(w), random.randrange(h)), (random.randrange(w), random.randrange(h))) for _ in range(5)]
window = pygame.display.set_mode((800, 800))
clock = pygame.time.Clock()
origin = window.get_rect().center
rays = createRays(origin)
obstacles = createObstacles(window)
move_center = True
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
obstacles = createObstacles(window)
if event.type == pygame.KEYDOWN:
move_center = not move_center
if move_center:
origin = pygame.mouse.get_pos()
rays = createRays(origin)
window.fill(0)
for endpoint in rays:
endpoint = intersect(obstacles, origin, endpoint)
pygame.draw.line(window, (128, 128, 128), origin, endpoint)
pygame.draw.circle(window, (255, 255, 255), origin, 10)
for start, end in obstacles:
pygame.draw.line(window, (255, 0, 0), start, end)
pygame.display.flip()
pygame.quit()
exit()

Pygame: How do I apply Separating Axis Theorem (SAT) to Rotating Squares?

I don't want the code (I really do want the code), but can someone explain to me how I can create the diagonal line to see if there's a gap? I know we have to use vectors, but I don't know how to do that using python
So, using the logic of Separating Axis Theorem that if you cant draw a line in between 2 squares then they are overlapping and colliding. I made something close, its not perfect but its close, I also haven't accounted for rotation of squares but if you find a way to find the vertices/corners of the square, then this could easily work. The way i did it was that i turned the squares into lines and drew a line directly in the middle of the squares and at the normal of the line in between the squares, its a bit confusing but it makes sense once you see it. I then used line intersecting maths to find if they intersect.
import pygame
from pygame.locals import *
from pygame import Vector2
pygame.init()
screen = pygame.display.set_mode((500,500))
#check if 2 lines are intersecting
def LineIntersect(line1, line2):
#the math is from wikipedia
x1 = line1[0].x
y1 = line1[0].y
x2 = line1[1].x
y2 = line1[1].y
x3 = line2[0].x
y3 = line2[0].y
x4 = line2[1].x
y4 = line2[1].y
den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if den == 0:
return
t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / den
u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / den
if t > 0 and t < 1 and u > 0 and u < 1:
pt = Vector2()
pt.x = x1 + t * (x2 - x1)
pt.y = y1 + t * (y2 - y1)
return pt
return
#class for sqaure
class square:
def __init__(self,x,y,w):
self.x = x
self.y = y
self.w = w
self.centerx = self.x + w//2
self.centery = self.y + w//2
self.col = (255,0,0)
def Draw(self, outline = False):
if outline:
self.Outline()
else:
pygame.draw.rect(screen,self.col,(self.x,self.y,self.w,self.w))
def Outline(self):
for point1, point2 in self.Lines():
pygame.draw.line(screen,sqr2.col,point1,point2,1)
#get the lines that make up the square, the outline/perameter
def Lines(self):
lines = []
lines.append((Vector2(self.x,self.y),Vector2(self.x+self.w,self.y)))
lines.append((Vector2(self.x,self.y),Vector2(self.x,self.y + self.w)))
lines.append((Vector2(self.x + self.w,self.y + self.w),Vector2(self.x+self.w,self.y)))
lines.append((Vector2(self.x + self.w,self.y + self.w),Vector2(self.x,self.y + self.w)))
return lines
#draw a line inbetween the 2 squares
def DrawLineInBetween():
#draw a line between the 2 squares, get gradient
#to avoid divide by zero
if abs(sqr1.x - sqr2.x) == 0:
gradient = "infinity"
else:
#rise over run
#left - right = run
left = sqr1 if sqr1.x < sqr2.x else sqr2
right = sqr1 if left == sqr2 else sqr2
gradient = ((left.y - right.y)/abs(sqr1.x - sqr2.x))
#print("gradient:",gradient)
#get the middle point between the centers of the squares
middle = (max(sqr1.x + sqr1.w//2, sqr2.x + sqr2.w//2) - abs(sqr1.x - sqr2.x)//2,
max(sqr1.y + sqr1.w//2, sqr2.y + sqr2.w//2) - abs(sqr1.y - sqr2.y)//2)
#to avoid divide by 0
if gradient == 0:
point1 = Vector2(middle[0], middle[1] + 100)
point2 = Vector2(middle[0], middle[1] - 100)
elif gradient == "infinity":
point1 = Vector2(middle[0] - 100, middle[1])
point2 = Vector2(middle[0] + 100, middle[1])
else:
#get normal of line
gradient = -1/gradient
#print("normal:",gradient)
point1 = Vector2(middle[0] + 100, middle[1] + int(-100 * gradient))
point2 = Vector2(middle[0] - 100, middle[1] + int(100 * gradient))
#print(point1)
#print(point2)
#print(middle)
pygame.draw.line(screen,(0,255,0),point1,point2,1)
line = (point1, point2)
return line
sqr1 = square(100,100,50)
sqr2 = square(200,100,50)
Clock = pygame.time.Clock()
running = True
key = ""
while running:
screen.fill((0,0,0))
sqr1.Draw(outline=True)
sqr2.Draw()
line = DrawLineInBetween()
for sqr_line in sqr1.Lines():
pt = LineIntersect(line,sqr_line)
if pt:
pygame.draw.circle(screen,(0,255,255),(int(pt.x),int(pt.y)),5)
if key == "s":
sqr1.y += 1
elif key == "w":
sqr1.y -= 1
if key == "d":
sqr1.x += 1
if key == "a":
sqr1.x -= 1
pygame.display.update()
Clock.tick(60)
for e in pygame.event.get():
if e.type == pygame.QUIT:
pygame.quit()
running = False
if e.type == MOUSEBUTTONDOWN:
print(e.pos)
if e.type == KEYDOWN:
key = e.unicode
if e.type == KEYUP:
key = ""
doing rotating squares:
added rotation variable in square class, i used this answer to find the corners of the square, then once i have the corners, used the line intersetion.
Here is new class:
#class for sqaure
class square:
def __init__(self,x,y,w):
self.x = x
self.y = y
self.w = w
self.centerx = self.x + w//2
self.centery = self.y + w//2
self.col = (255,0,0)
self.rotation_angle = 0
def Draw(self, outline = False):
if outline:
self.Outline()
else:
pygame.draw.rect(screen,self.col,(self.x,self.y,self.w,self.w))
#this used the normal coordinate of an unrotated square to find new coordinates of rotated sqaure
def GetCorner(self,tempX,tempY):
angle = math.radians(self.rotation_angle)
rotatedX = tempX*math.cos(angle) - tempY*math.sin(angle);
rotatedY = tempX*math.sin(angle) + tempY*math.cos(angle);
x = rotatedX + self.centerx;
y = rotatedY + self.centery;
return Vector2(x,y)
def Outline(self):
for point1, point2 in self.Lines():
pygame.draw.line(screen,sqr2.col,point1,point2,1)
#new lines method, only changed to GetCorner()
def Lines(self):
lines = []
top_left = self.GetCorner(self.x - self.centerx, self.y - self.centery)
top_right = self.GetCorner(self.x + self.w - self.centerx, self.y - self.centery)
bottom_left = self.GetCorner(self.x - self.centerx, self.y + self.w - self.centery)
bottom_right = self.GetCorner(self.x + self.w - self.centerx, self.y + self.w - self.centery)
lines.append((top_left,top_right))
lines.append((top_left,bottom_left))
lines.append((bottom_right,top_right))
lines.append((bottom_right,bottom_left))
return lines
#chnaged to this as rotation rotates around center, so need to update both x and centerx
def Move(self,x =None, y = None):
if x:
self.x += x
self.centerx += x
if y:
self.y += y
self.centery += y
#get the lines that make up the square, the outline/perameter
#def Lines(self):
#lines = []
#lines.append((Vector2(self.x,self.y),Vector2(self.x+self.w,self.y)))
#lines.append((Vector2(self.x,self.y),Vector2(self.x,self.y + self.w)))
#lines.append((Vector2(self.x + self.w,self.y + self.w),Vector2(self.x+self.w,self.y)))
#lines.append((Vector2(self.x + self.w,self.y + self.w),Vector2(self.x,self.y + self.w)))
#return lines

Categories