Reputation: 67
So I tried to make an enemy turn around when hitting the wall and it's getting stuck.
This is the code for just the enemy: (The size of the screen is 1000 by 1000 btw)
xEnemy = random.randint(0,1000)
yEnemy = random.randint(0,1000)
#enemy
def enemy():
global xEnemy, yEnemy
pygame.draw.rect(screen,(255,0,0),(xEnemy,yEnemy,15,15))
if xEnemy > 0 and xEnemy < 1000:
xEnemy -=velEnemy
if xEnemy < 0 and xEnemy > 10:
xEnemy += velEnemy
Upvotes: 1
Views: 77
Reputation: 210889
You have to change the velocity if xEnemy > 1000
or xEnemy < 0
. If xEnemy > 1000
, the velocity has to become negative. If xEnemy < 0
, the velocity has to become positive. The absolute amount of the velocity can be get with abs(velEnemy)
. Don't forget global velEnemy
def enemy():
global xEnemy, yEnemy, velEnemy
if xEnemy < 0:
velEnemy = abs(velEnemy)
if xEnemy > 1000:
velEnemy = -abs(velEnemy)
xEnemy += velEnemy
pygame.draw.rect(screen, (255,0,0), (xEnemy, yEnemy, 15, 15))
Upvotes: 1