Random movement on a KinematicBody2D

Attention Topic was automatically imported from the old Question2Answer platform.

Hi, I have an enemy in a topview game. At first I had the enemy as a rigidbody but then it slowed down on collisions so I turned it into a kinematic body but now I have no idea how to make the enemy move in a random direction and so it bounces off other rigidbodies.

This is how far I’ve come but this isn’t working out at all…

``````export (int) var speed

var rng = RandomNumberGenerator.new()
var velocity = Vector2(speed, 0)
var direction = rotation + PI / 2

rng.randomize()
direction += rng.randf_range(-PI / 4, PI / 4)
get_node(".").rotation = direction

func _physics_process(delta):
move_and_collide((velocity * delta).rotated(direction))
# Bounce
var collision = move_and_collide(velocity * delta)
if collision:
velocity = velocity.bounce(collision.normal)
if collision.collider.has_method("hit"):
collision.collider.hit()
``````
2. You don’t need to use `get_node(".")`, you can just set the rotation directly.
3. IIRC, the velocity you pass into `move_and_collide` needs to be relative to the kinematic body. So because you are rotating the kinematic body, you should not be rotating/bouncing the velocity (The bounce logic should instead change the rotation of the body). Or you can leave the rotation alone, and just rotate the velocity. Don’t do both.
4. You’re calling `move_and_collide` twice, once rotating it, and once not. Both calls to it will move the body, but only one actually causes bouncing. I’m not sure that the engine will properly handle two calls to it in a row, so you should really only be calling it once in the function.