I am trying to make a tank rotation system where the top rotations top down game

Godot Version

Question

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).

Here is the movement code
extends CharacterBody2D

var speed = 600
var rotation_speed = 1.5

func _ready():
pass
func _physics_process(delta):
var move_input = Input.get_axis(“Forward”, “Backwards”)
var rotation_direction = Input.get_axis(“Turn Left”, “Turn Right”)
velocity = transform.x * move_input * speed
rotation += rotation_direction * rotation_speed * delta
move_and_slide()

You’re on the right track.

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):
Node hierarchy

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.

Here’s how this looks in-engine:
In-engine view of the rotating tank turret

1 Like

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?

Ah, yes, I fear you’re out of luck there. You’d really need the turret as a separate sprite of sorts. There’s no way you could rotate it standalone.

I have implemented the code into my new tank model but when I move my cursor the turret rotates in the opposite direction is there any fix to this?