简体   繁体   English

自己在python中移动对象

[英]moving objects in python on its own

I am trying to make an object(a ship) to move on its own with its own speed and random direction, but after looking at the internet, I could only find objects that are moved manually. 我试图使一个物体(一艘船)以自己的速度和随机方向自行移动,但是在看完互联网之后,我只能找到手动移动的物体。 I tried using randrange to maybe make it move randomly 我尝试使用randrange使其随机移动

    def on_mouse_press(self, x, y, button, modifiers):
    if button == arcade.MOUSE_BUTTON_LEFT:
        self.player_sprite.center_x = random.randrange(800)
        self.player_sprite.center_y = random.randrange(800)

but it needs multiple clicks and my ship just jumped around. 但它需要多次点击,我的飞船才跳来跳去。 Could someone teach me how to do it properly? 有人可以教我如何正确地做吗? thank you. 谢谢。

After trying to implement the recommendation from below i came up with this: 在尝试从下面实施建议后,我想到了这一点:

    def on_mouse_press(self, x, y, button, modifiers):
    while self.score != 1:
        while button == arcade.MOUSE_BUTTON_LEFT:
            self.player_sprite.center_x += random.choice([-1, 1])
            self.player_sprite.center_y += random.choice([-1, 1])
        if self.score == 1:
            break
    print("box has been found!")

but now the program would not run at all and gives an exit code of -805306369. 但现在该程序将完全无法运行,并给出-805306369的退出代码。

To move your ship smoothly, you need to move it one step at a time. 为了使船舶平稳移动,您需要一次移动一步。

random.randrange(800) will give you random value from 0 to 800 and that's why your ship is jumping. random.randrange(800)将为您提供0到800之间的随机值,这就是您的飞船跳跃的原因。

What you need is something like this. 您需要的是这样的东西。

 if button == arcade.MOUSE_BUTTON_LEFT:
        self.player_sprite.center_x += random.randrange(-1,2)
        self.player_sprite.center_y += random.randrange(-1,2)

random.randrange(-1,2) will give you either -1, 0 or 1 value. random.randrange(-1,2)将为您提供-1、0或1值。

  • Adding that to x axis it will either move left , right or won't move at all. 将其添加到x轴向左向右移动或完全不移动。
  • For y axis it will either move up , down or won't move. 对于y轴 ,它将向上向下移动或不移动。

In case if you alway want to move. 万一您始终想搬家。 You can change random.randrange(-1,2) to random.choice([-1, 1]) 您可以将random.randrange(-1,2)更改为random.choice([-1, 1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM