在python教材《Python编程:从入门到实践》这本书中的第十二到第十四章的小游戏教程的基础上,我试着根据教程来做一个我自己感兴趣的游戏,游戏内容都是我自己比较喜欢的元素。之后的一段时间我将记录游戏的制作过程。

同样的,我设定了游戏敌人,游戏敌人的移动速度我设定为self.amary1_speed_factor = 0.1,然后我最开始使用的是下面这串代码来实现敌人向着游戏角色靠拢的效果。

def attract(self, kate, Newsetting):
        distance_x = self.rect.centerx - kate.rect.centerx
        distance_y = self.rect.centery - kate.rect.centery
        distance = (distance_y ** 2 + distance_x ** 2) ** 0.5
#计算敌人和玩家kate之间的距离 if distance != 0: attract_x = self.Newsetting.amary1_speed_factor * (distance_x / distance) attract_y = self.Newsetting.amary1_speed_factor * (distance_y / distance)
#使用三角函数计算出横坐标和纵坐标需要移动的距离 self.rect.centerx
-= attract_x self.rect.centery -= attract_y
#横纵坐标分别移动

但是出错了,敌人amary1生成后站在原地不动,在网上查了一下以后我知道了rect这一类的内容只能是整数,就算给了小数也会自动取最近的整数。然后根据网络上的别人的解答,说是需要使用别的变量来储存rect.x和rect.y,于是

     self.centerx =float(self.rect.centerx)
        self.centery =float(self.rect.centery)


    def attract(self, kate, Newsetting):
        distance_x = self.centerx - kate.rect.centerx
        distance_y = self.centery - kate.rect.centery
        distance = (distance_y ** 2 + distance_x ** 2) ** 0.5

        if distance != 0:
            attract_x = self.Newsetting.amary1_speed_factor * (distance_x / distance)
            attract_y = self.Newsetting.amary1_speed_factor * (distance_y / distance)

            self.centerx -= attract_x
            self.centery -= attract_y

            self.rect.centerx = self.centerx
            self.rect.centery = self.centery

使用了self.centerx和y来储存浮点数,再在最后赋值回来。这样就解决了只能整数移动的问题。

其实这个问题在书中教程已经解决了,书中已经使用过了类似的方法,只是没有说明为什么,这对于没有听课只有自学的人来说是很难搞懂为什么的。

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/mxyj/p/17583884.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!