We need a code for the 8-way movement of the NPC

Godot Version

4.2.1 stable

Question

Good evening. I wanted to write code for characterbody2d so that it could move in 8 directions at a random moment, but I can’t do it.

extends CharacterBody2D

var speed = 100
var direction = Vector2.ZERO

func _process(delta):
if direction == Vector2.ZERO:
direction = Vector2(randf_range(-1, 2), randf_range(-1, 2)).normalized()

var movement = direction * speed * delta
move_and_slide(movement)

This is what my code looks like, but it doesn’t work

What happens when you run the code? Do you get any error or does it just behave incorrectly? And in your question, only a part of your code is posted formatted as code. Could you please update your question and format all your code as code?

The game starts without errors, but characterbody2d does not move. I’m sorry, but how do I format text into code?

move_and_slide doesn’t take arguments. Try this:

velocity = direction * speed * delta
move_and_slide()

Thank you. but it didn’t help. in general, I have an empty scene consisting only of: characterbody2d, sprite2d, collision2d. maybe you need to add something to make it work?

Put triple backticks around it: ``` before and after the code

1 Like

Could you provide a screenshot of the scene tree and the script?

just watch this:

1 Like

There are at least a few things you can improve there.

Your base code working would be:

extends CharacterBody2D

var speed = 100
var direction = Vector2.ZERO

func _physics_process(_delta):
	direction = Vector2(randf_range(-1, 2), randf_range(-1, 2)).normalized()
	velocity = direction * speed
	move_and_slide()

Basically your problem is that you were just updating direction just once becouse of the if. Once you asign the random direction it is ZERO no more, so it would not update the value on next process cycle. In adition your calculation of the direction vector is not unitary, it is not (-1, 0) for instance, it is getting things like (0.03, 0.1), so if you multiply your speed with nearly zero value, it is going to be very, very slow.

So, a few things to tune there. Hope this helps you!

1 Like

thanks bro

the problem is solved, the mob is moving, but only it is moving left-down, how to make them move with some kind of intermittency

I guess you mean giving it some kind of randomness during time. Well, thats a matter of how you want the IA to be for your game. A pretty basic approach could be adding a Timer node, setting a few seconds and calling a method to randomize the direction on the timeout signal.

High level:

image

extends CharacterBody2D

var _direction: Vector2

@onready var timer = $Timer

func _ready():
	timer.connect("timeout", _on_timer_timeout)

func _on_timer_timeout():
	_direction = Vector2().normalized() # Your random direction generator
1 Like

Thank you very much, little brother