Topic was automatically imported from the old Question2Answer platform.
Asked By
rubendw03
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)
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.
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:
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.