简体   繁体   English

Pygame:将对象移向位置

[英]Pygame: Move object towards position

Is there an algorithm to change a set of coordinates to make it move towards another set of coordinates?是否有一种算法可以更改一组坐标以使其向另一组坐标移动?

Like, if I have ax,ay=(20,30) and bx,by=(40,60)比如,如果我有ax,ay=(20,30)bx,by=(40,60)

I can't seem to wrap my head around this.我似乎无法解决这个问题。 How can I change ax and ay (over time) to equal bx and by ?我怎样才能改变axay (随着时间的推移)等于bxby (Preferably an algorithm achievable in python.) (最好是可以在 python 中实现的算法。)

It's pretty easy if you think about it.如果你考虑一下,这很容易。 To create the illusion of movement you need to create an animation - that is, moving the object step by step .要创建运动错觉,您需要创建动画 - 即逐步移动对象。

The object needs to move 20 pixels horizontally ( bx - ax = 20 ) and 30 pixels vertically ( by - ay = 60 ).对象需要水平移动 20 个像素( bx - ax = 20 )和垂直移动 30 个像素( by - ay = 60 )。 Now, you need to define how many steps the object will spend moving.现在,您需要定义对象将花费多少移动。 That essentially depends on the framerate of your game, if you want the animation to last 1 second and your game runs at 25fps, the animation will take 25 steps.这主要取决于您游戏的帧率,如果您希望动画持续 1 秒并且您的游戏以 25fps 运行,则动画将需要 25 步。 If your game does not have a fixed framerate but something else, you'll need to compute the amount of movement for each iteration of the game loop depending on the elapsed time from the last frame.如果您的游戏没有固定的帧率而是其他的东西,您将需要根据从最后一帧开始的时间来计算游戏循环每次迭代的移动量。

Let's suppose we're runing at a fixed speed of 25fps.假设我们以 25fps 的固定速度运行。 In that case, you'd need to do something like:在这种情况下,您需要执行以下操作:

dx, dy = (bx - ax, by - ay)
stepx, stepy = (dx / 25., dy / 25.)

Now, stepx and stepy have the amount of movement needed in each step.现在, stepxstepy具有每一步所需的移动量。 What you need to do is add that in each iteration of the game loop:您需要做的是在游戏循环的每次迭代中添加:

# In each iteration:
object.set_position(object.x + stepx, object.y + stepy)
steps_number = max( abs(bx-ax), abs(by-ay) )

stepx = float(bx-ax)/steps_number
stepy = float(by-ay)/steps_number

for i in range(steps_number+1):
    print int(ax + stepx*i), int(ay + stepy*i)

result:结果:

20 30
20 31
21 32
22 33
22 34
23 35
24 36
24 37
25 38
26 39
26 40
27 41
28 42
28 43
29 44
30 45
30 46
31 47
32 48
32 49
33 50
34 51
34 52
35 53
36 54
36 55
37 56
38 57
38 58
39 59
40 60

As you are using pygame, then you can use vectors to move your object on the screen.当您使用 pygame 时,您可以使用矢量在屏幕上移动您的对象。

import pygame as pg

vec = pg.math.Vector2
a = vec(20, 30)
b = vec(40, 60)
a += b

Put it in your loop and add speed to slow it down.把它放在你的循环中并增加速度以减慢它的速度。 Your object will move toward the "b" point and will pass it when it reachs that point.您的对象将向“b”点移动,并在到达该点时通过它。

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

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