Reputation: 379
I wrote some code to try and implement one function that creates a triangle using the coordinates of the center of the screen and in this case it corresponds to the center of the triangle aswell, this coordinates are identified as "cx" and "cy" since the window is 800 x 600 cx = 400 and cy = 300. with this i created a "first point" that has the same x coordinate of the center but its 100 pixels above the center, now using the center and this first point i tried to calculate where the other point should be. here is the code:
def triangle(cx,cy):
angle = 2*math.pi/3
first_point_x = cx
first_point_y = cy + 100
vertex = [first_point_x,first_point_y]
for i in range(2):
newx = (vertex[i*2]-cx) * math.cos(angle) - (vertex[i*2+1]-cy) * math.sin(angle)
newy = (vertex[i*2+1]-cy) * math.cos(angle) + (vertex[i*2]-cx) * math.sin(angle)
vertex.append(newx)
vertex.append(newy)
return vertex
But for some reason the array gives negative values and numbers that overall dont correspond to what i wanted. Any help whould be appreciated.
Upvotes: 1
Views: 503
Reputation: 211220
What you actually do is to compute a vector from (cx, cy) to the last point in the array and to rotate the vector by 120°. But you missed to add the vector to (cx, cy) before you append the point to the list:
newx = (vertex[i*2]-cx) * math.cos(angle) - (vertex[i*2+1]-cy) * math.sin(angle)
newy = (vertex[i*2+1]-cy) * math.cos(angle) + (vertex[i*2]-cx) * math.sin(angle)
newx = cx + (vertex[i*2]-cx) * math.cos(angle) - (vertex[i*2+1]-cy) * math.sin(angle)
newy = cy + (vertex[i*2+1]-cy) * math.cos(angle) + (vertex[i*2]-cx) * math.sin(angle)
Compute the vector from the center to the last point
vx = vertex[i*2] - cx
vy = vertex[i*2+1] - cy
Rotate the vector
rotated_vx = vx * math.cos(angle) - vy * math.sin(angle)
rotated_vy = vy * math.cos(angle) + vx * math.sin(angle)
Compute the new point
newx = cx + rotated_vx
newy = cy + rotated_vy
Upvotes: 1