0 votes

I'm working on a game in wich I want a dot to move in a field, when it hits the border walls it should bounce off. I've got all these things to work except for the RigidBody2D (the dot) to move at a constant pace.

This is the basic script:

extends RigidBody2D

export (int) var speed
signal infected
var rng = RandomNumberGenerator.new()


func _ready():
    set_bounce(1)
    rng.randomize()
    var direction = rng.randf_range(-PI, PI)
    get_node(".").rotation = direction
    get_node(".").set_linear_velocity(velocity.rotated(direction))

I tried this to give the RigidBody2D a constant pace but it didn't work out:

extends RigidBody2D

export (int) var speed
signal infected
var rng = RandomNumberGenerator.new()
var velocity = Vector2(speed, 0)

func _ready():
    set_bounce(1)
    rng.randomize()
    var direction = rng.randf_range(-PI, PI)
    get_node(".").rotation = direction
    get_node(".").set_linear_velocity(velocity.rotated(direction))

func _physics_process(delta):
    if get_node(".").linear_velocity <= Vector2(speed, 0):
        velocity += Vector2(1, 0)
        get_node(".").set_linear_velocity(velocity)

Does someone know a way to do this?

asked Mar 21 in Engine by rubendw03 (41 points)

1 Answer

0 votes

The linear velocity of a RigidBody is damped by default. You can either disable that individually for one object by setting linear_damp = 0 or change the project default under Project Settings > Physics > 2D > Default Linear Damp.

answered Mar 21 by njamster (8,128 points)

I had the damp already set to 0, i think the problem is that when the dot collides with the walls or other dots that it slows down. That's why I tried to fix it with:

func _physics_process(delta):
    if get_node(".").linear_velocity <= Vector2(speed, 0):
        velocity += Vector2(1, 0)
        get_node(".").set_linear_velocity(velocity)

Is there a way to fix that?

when the dot collides [...] it slows down

Have you set friction to zero? I cannot reproduce your problem.

I've put the friction to zero on al dots, but still they lose pace.

Here's the video, the red dot is supposed to keep its pace.
https://youtu.be/Cx64erzlyE8

That's the law of conservation of momentum. If two balls move with different velocity and collide, the will swap their velocity-amplitude (in addition to changing their direction). Judging from your video, there's no real reason you're using a RigidBody2D in the first place though. If you're not interested in realistic physics, just use a KinematicBody2D. They can bounce from other bodies as well.

Oh okay! Thanks for the help!!!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.