Need Help with my Balls

Godot Version

4.7.2

Question

I'm trying to recreate those ball battle videos on youtube, i.e. Earclacks, Ham's Ball Battles, etc. Whenever my balls collide, they sometimes stick together and bug out before finally having a proper collision. How do I ensure that they bounce around properly, and collide with one another only once? Here's my physics process:

public override void _PhysicsProcess(double delta)

    {




if (dead) return;




Vector2 velocity = Velocity;




// Add the gravity.

if (!IsOnFloor())

        {

velocity += GetGravity() / 2 * (float)delta;

        }




Vector2 unclampedCollideVector = new(direction.X * (currentSpeed * (float)delta), direction.Y * (currentSpeed * (float)delta));




float clampX = Mathf.Clamp(unclampedCollideVector.X, -maxSpeed * (float)delta, maxSpeed * (float)delta);

float clampY = Mathf.Clamp(unclampedCollideVector.Y, -maxSpeed * (float)delta, maxSpeed * (float)delta);




Vector2 collideVector = new(clampX, clampY);




KinematicCollision2D collision = MoveAndCollide(collideVector);

if (collision != null) {

direction = direction.Bounce(collision.GetNormal());

//GlobalPosition += collision.GetNormal() * 2.0f;

        }

velocity.X = Mathf.MoveToward(Velocity.X, 0, -Speed);




Velocity = velocity;

MoveAndSlide();

    }

Thank you for any assistance. Ask any questions you have for clarification.

Very difficult to tell from your code

I’d guess that the CharacterBody2D are assuming anything below them is a “moving platform” you should try setting the CharacterBody2D’s “Motion Mode” to “Floating”

Looks like the ball moves twice every frame, once with MoveAndCollide and then again with MoveAndSlide, and the second move can shove it straight back into the ball it just hit. I’d stick to one.

It also helps to only bounce if you’re actually moving into the other ball, otherwise the same contact can flip you twice:

if (collision != null && direction.Dot(collision.GetNormal()) < 0)
    direction = direction.Bounce(collision.GetNormal());

And MoveToward(Velocity.X, 0, -Speed) has a negative step, which moves the value away from 0, so that line speeds X up rather than slowing it