I need help making ai go left and right!

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By EitherRock

Im making a very simple soccer game. The player tries to kick the ball into the goal while the goalie tries to block it. All I want the goalie to do is go left to right. when the goalie reaches the edge of the screen while going right, I want him to start going left until he hits the other side etc. I have a collision shape on him but I just cant figure out the code to make him move how I want.

Share what you have so far. It’s hard to know what to tell you if we can’t see what code you have already for movement.

kidscancode | 2018-07-02 23:30

That’s actually part of the problem im having. I can do my own player movement but I don’t know how to make a npc move by itself. so I don’t have any code that works. I also had people suggests using animation for it, but I haven’t gotten around to learning animation yet

EitherRock | 2018-07-03 01:54

:bust_in_silhouette: Reply From: Andrea

The simpler way i can think is attaching a code to the goalie node (KinematicBody), and inside:

var going_left=true
var extreme_left=-100
var extreme_right=100
var speed=1

func _process(delta):
  	if going_left:
  	  move_and_collide(Vector2(-speed,0))
 	  if position<=extreme_left:
 	   	  going_left=false
    else:
  	  move_and_collide(Vector2(speed,0))
 	  if position>=extreme_right:
 	    	going_left=true

You can do it also with CollisionShape, and likely in a ton of other ways.
If you want to do it with collision shape you should place other bodies at the right and left of your goalie, when the goalie touch them it will fire a signal: you can see the signal clicking on him on the scene tree, look at the inspector and select the “Node” tab.
Double click on the signal (it should be input_event) and connect it with any script.
When the goalie touch the other object the signal will fire, and the code you write below will start

Thank you! This was very helpful :slight_smile:

EitherRock | 2018-07-03 15:49

:bust_in_silhouette: Reply From: duke_meister

Use a Path2D node.