Hey ArthurER:
I was able to get something working that I think approximates what you're looking for. The key was to use a single KinematicBody2D with multiple collision shapes so that all the collision shapes are updated with the same moveandslide() function. Here's what my tank scene looks like:
KinematicBody2D (Name: "TankBody")
- Sprite (for the tank body)
- CollisionShape2D (Name: "TankBodyShape", for the tank body)
- CollisionShape2D (Name: "TankTurretShape", for the tank turret)
> Sprite (for tank turret)
- Camera2D
My obstacles are also pretty simple:
StaticBody2D
- Sprite
- CollisionShape2D
The messy part is the tank script which I will copy in a separate answer for you to look at. You're welcome to copy it and use it in your project however you see fit.
Your first problem was that when your tank collided with an obstacle, the turret got displaced from the tank's body. The way I solved this issue was to make the turret into a second CollisionShape2D so that Godot treats it as part of the same kinematic body. When you structure the tank in this way, both the tank's body and turret will stop when the turret collides with an obstacle. Unfortunately, making rotation work was a bit trickier, but I'll spare you the details and let you see for yourself.
The script below is mildly customizable. If you want the tank to move when the turret is rotated against an object, set "tankmovewhenturretrotates" to true. Otherwise, when it's false, the turret will stop rotating when it hits an object and only displace the tank by a small amount. It also lets you adjust how quickly the tank rotates towards your mouse cursor, how fast the tank moves, and how far the turret is from the main body of the tank. The script is designed to make the turret rotate around the center of the tank, so position your CollisionShape2D accordingly.
Note: This all works on one collision layer.
I tried doing a write up explaining how this works, but it's late and I am sleepy. I hope this gives you a good base to work off of. If you have any questions feel free to let me know! Happy programming.