Time for physics, which means that everything will go smoothly and I won’t have any issues. First things first, I need to add collisions to my walls, so I changed the structure a little bit, using what I learned about balls.
To my field object I addedStaticBody2D nodes that would become my new walls. The existing sprite objects become children of that and I just need to also add to each wall a CollisionShape2D that is the same size as the sprite. Quick enough.
Now, I haven’t done anything in code to actually use the collision, so I’m not expecting much, but just for fun let’s go ahead and run the game and see what happens.
I’ll be honest, when I pressed run I wasn’t expecting this. I kind of just figured that the ball would pass through the wall like before. Then, I remembered something. In the code I wrote yesterday I move the ball using move_and_slide(), which would explain why it’s sliding along the floor when we are trying to apply that velocity.
Another similar method exists, move_and_collide, so I tried that. When I used move_and_collide() the ball instantly snaps to the wall and stops moving… That’s weird.
A bit of googling later revealed an… interesting design choice. While move_and_slide() automatically calculated velocity using the delta, move_and_collide() does not. I can’t say I agree with that design decision, but that’s how the scripting works, so instead I’ll multiply my velocity by the delta.
So, with that now added, let’s go ahead and run this again.
Ok, so it does sort of jitter and continue to move along the bottom, but that’s ok. One of the nice things about using move_and_collide is that it returns a collision object when a collision occurs. I can use that to detect when the ball hits the wall, and then use the information about the collision in question to have the ball bounce off. Here is what that looks like.
Three main changes here. First is I moved the velocity definition to the _init() function, this way I just set the starting movement of the ball. Second, velocity is not directly modified by the speed and delta, instead I added a local variable to hold that. Lastly, I check the collider that comes back from move_and_collide, and if it’s not null I simply use the normal of the collision to modify the velocity. Adding twice the normal to the velocity seemed to do the trick. Now, when I run it (with an increased speed so we can get on with it faster), it looks like this.
And that’s a success! The ball bounces off walls now, so that’s progress. Tomorrow the plan is to add paddles that will be player controlled. Until then!