Add a random angle when bouncing

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

In a shoot them up I have an enemy (a boss) that I want to be bouncing around in a way that seems random.

So I made it into a RigidBody2D, and I disposed around it some invisible StaticBody2D. I have a physics material for bounce.

It works fine, however I would like it to be less predictible. So when it collides with the screen border (implemented with a StaticBody2D) I want to add a small, random angle to the bounce. So instead of a perfect bounce, we get something less predictible.

Any idea how to implement it?

I’ve looked into writing code on collision in GDScript but I can’t find much info on RigidBody2D, apparently all the collision-related methods are only defined on KinematicBody2D.

:bust_in_silhouette: Reply From: sash-rc

At least you have a linear_velocity vector.
When a body starts bouncing (after collision) you should add some random force in normal direction (perpendicular) to body’s velocity.

  var rb : RigidBody2D # your body
  var v : Vector2 = rb.get_linear_velocity().normalized().rotated(PI/2.0)
  rb.add_central_force(v * your_random_float)

thank you, but how do I detect the collision? All the references I found are for KinematicBody2D and don’t work for RigidBody2D

takochanfr | 2021-07-27 07:33

Technically, this is another question.

Easiest one is to use body’s signals body_entered / body_exited.
RigidBody2D — Godot Engine (stable) documentation in English

In any case, just note, collision is not a momentary, but a continuous action, as well as there could be several colliding bodies at a moment. So you need to monitor both start and finish events (for a proper counterpart body).

sash-rc | 2021-07-27 08:19