I have one component which is tank and inside I made the physics and movement. but I am confused on how I would make part of the tank move when they are one image(only the cannon).
I’d typically use Godot’s node hierarchy, as this will save you from doing lots of math (as the engine will do it for you):
Note I’ve added a separate Sprite2D for the barrel simply because I used Kenney’s Top-down Tanks Redux. It could obviously be part of the turret sprite, too.
Make sure the turret’s point of origin is in the center of the turret (i.e. where it should rotate around).
Next, all we have to do is just expand your script by a little bit:
# Retrieve cursor position
var cursor_position = get_viewport().get_mouse_position()
# Get direction/rotation from tank to cursor
var turret_rotation = position.angle_to_point(cursor_position)
# Assign the turret rotation (but correct it by the body rotation)
$TurretSprite2D.rotation = turret_rotation - rotation
Instead of using the mouse cursor, you could obviously just change the turret’s rotation similar to how you rotate the tank body. In this case you wouldn’t have to do the - rotation correction, though.
Why do you have a seperate sprite for the barrel? Oh and my tank is one image which contains the turret and everything so I don’t know how to separate it from the image which is my main problem
It’s really just separate because I had two separate textures that I wanted to combine without extra editing.
Sounds like I misunderstood your issue. Is the turret next to the tank body in the same image? Or is it already attached? In first case you can just change the visible rectangle for the Sprite2D, in second case this isn’t really possible.
Can you share a lower resolution or slightly distorted version of the image texture in question?