我有从 2 个点画一条线的代码;一个位于屏幕的中下方,另一个位于鼠标指针上。我试图通过不超过我设置的长度参数来限制该点。代码如下:
import pygame
import Resources as r
import math as m
pygame.init()
class Segment():
def __init__(self, _screen, _id, _start_pos, _length):
self.screen = _screen
self.id = _id
self.start_pos = _start_pos
self.length = _length
def update(self):
if self.id == 1:
mouse_pos = pygame.mouse.get_pos()
self.angle = m.atan2(mouse_pos[1]-self.start_pos[1],mouse_pos[0]-self.start_pos[0])
self.a = self.start_pos
self.b = (m.cos(self.angle)*self.length, m.sin(self.angle)*self.length)
self.draw_line(self.a, self.b, r.black, 4)
def draw_line(self, start, end, color, width):
if self.id == 1:
pygame.draw.line(self.screen, color, start, end, width)
def get_data(self):
return (self.start_pos, self.end_)
当我运行这个程序时,我看到的结果与我预期的完全不同,它与我的鼠标不一致,并且通常只是在移动鼠标时来回振荡。
最佳答案
self.b
是根据原点0, 0计算的,而不是self.start_pos
。
将self.a
中的坐标添加到self.b
。
关于Python 正弦和余弦给出错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47644279/