Random movement on a KinematicBody2D

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

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

func _ready():
	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()
:bust_in_silhouette: Reply From: Avantir

A few things:

  1. By defining direction as rotation + PI / 2, then later setting rotation to direction, you’re implicitly adding PI/2 to the rotation for no apparent reason
  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.

Thanks! I’ve changed the script and it’s working now. The problem is that I’m copying scripts and sewing them together. But now it works fine thanks!

rubendw03 | 2020-03-22 22:50