Zach Hatch
Zach Hatch

Reputation: 7

i need some basic godot enemy movement script in godot 4.0 or a way to make the enemy movement in godot 4.0

All I need is an enemy movement script or some instructions on how to make it. Your efforts to help me will be greatly appreciated.

Personal Experience: I'm kind of still new but are gaining knowledge pretty quickly with YouTube tutorials (which I can't find on this topic)

Upvotes: 0

Views: 3609

Answers (1)

TheJalfireKnight
TheJalfireKnight

Reputation: 101

I think the easiest thing to use would be a CharacterBody. I am going to assume you are doing this in 2D so we will be using a CharacterBody2D for this. Steps to making basic enemy movement:

  1. First thing you want to do is create a variable to define the speed at which an enemy moves. Example: var speed = 10
  2. Next you want to create 4 functions for the 4 movement directions.

Example:

func move_up():
func move_down():
func move_left():
func move_right():
  1. Next we want to make each function move the enemy in a different direction. To do this we are going to use the CharacterBody's built in velocity variable. To move up and down we have to move along the y-axis. Lets turn this into functions:

    func move_up():
        velocity.y = -speed
    
    func move_down():
        velocity.y = speed
    

    Now we have to make the other 2 functions. To move left and right we have to move along the x-axis. Here are the functions for that:

    func move_left():
        velocity.x = -speed
    
    func move_right():
        velocity.x = speed
    
  2. Now that we have those functions made, we need to call them to make the enemy move:

    func _physics_process(delta):
        move_down()
    

    The enemy won't move yet because we need to add the move_and_slide() function at the after changing the velocity to actually move the CharacterBody.

    func _physics_process(delta):
        move_down()
    

This is the final code:

extends CharacterBody2D
var speed = 10

func move_up():
    velocity.y = -10

func move_down():
    velocity.y = 10

func move_left():
    velocity.x = -10

func move_right():
    velocity.x = 10

func _physics_process(delta):
    move_down()
    move_and_slide()

Upvotes: 1

Related Questions