我试图有代码,我可以点击一个精灵,点击一个位置,它会移动一段时间。你知道吗
这是我的密码:
def update(self, mousePosX, mousePosY, mouseDown):
#Walk
self.walkCool += 1
self.rect.x += self.xIncrement
self.rect.y += self.yIncrement
if self.rect.x == self.targetX:
self.yIncrement = 0
self.xIncrement = 0
if self.selected == True:
pg.draw.line(screen, (18, 219, 255), (self.rect.x + self.size//2, self.rect.y + self.size//2) , (mousePosX, mousePosY), 3)
if mouseDown[0] and self.walkCool > 20:
self.targetX = mousePosX
self.targetY = mousePosY
self.dy = self.targetY - self.rect.y
self.dx = self.targetX - self.rect.x
print(self.dx,self.dy)
self.yIncrement = self.dy/self.dx
if self.dy > 0 and self.dx < 0:
self.yIncrement = self.yIncrement * -1
if self.dx < 0:
self.xIncrement = -1
elif self.dx > 0:
self.xIncrement = 1
else:
self.xIncrement = 0
上面的代码是针对我的sprite类中的update函数的(每次在我的update循环中调用它)。我的问题是,如果我得到一个dx/dy<;1,那么它似乎没有移动到确切的单击位置,而且我也不能让它移动到(-,+)象限。不知道如何解决这些问题。你知道吗
首先使用vectors让你的生活更轻松。当用户单击鼠标按钮时设置精灵的目标。计算到目标的向量(这里称为
heading
),将其规格化并缩放到所需的速度,然后将其用作速度向量。当精灵接近目标时,你需要减慢它的速度,否则它会快速地来回移动。你知道吗相关问题 更多 >
编程相关推荐