'Making an object move towards another moving object
I am currently using pygame and I have made an enemy and a player. I want the enemy to be able to move straight toward the player. The best solution I could find was:
if playerX > enimeX:
enimeX_change = 0.1
else:
enimeX_change = -0.1
if playerY > enimeY:
enimeY_change = 0.1
else:
enimeY_change = -0.1
This does make the enemy go toward the player, though it goes until it has an even Y or X value, then goes straight, so it's a curvy path. I want it to be a straight line from the current position to the players' position. Can someone help? Note:I am fairly new to coding so please dumb it down for me ha-
Solution 1:[1]
anyway you have the code you need but let me make it a function for you
def enmy_follow_player(playerX, playerY, enemy_list):
"""
If you want multiple enemies to follow the player, you can use a loop like
this and check them all one by one.
"""
for enemy in enemy_list:
if playerX > enemy[0]:
enemy[0] -= 0.1
else:
enemy[0] += -0.1
if playerY > enemy[1]:
enemy[1] -= 0.1
else:
enemy[1] += 0.1
position_of_all_enemy =[[100,100],[100,100],[100,100]]#store all enemy position in a list
player_pos = [100,100]
while True:
follow = enmy_follow_player(player_pos[0],player_pos[1],position_of_all_enemy ) #you need to call this function continuously in a loop
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Django |
