Godot Version
4.2.1
Question
Im making game where player is car and on the top there is turret what is rotating to the mouse cursor but problem is when i turn car to the left or right turret is still looking at the old mouse cursor location
script
extends CharacterBody2D
@onready var bullet = preload(“res://bullet.tscn”)
var wheel_base = 70
var steering_angle = 101
var steer_angle
var engine_power = 1000
var friction = -0.9
var drag = -0.0015
var braking = 150
var max_speed_reverse = 250
var slip_speed = 400
var traction_fast = 0.1
var traction_slow = 0.7
var acceleration = Vector2.ZERO
@onready var turret = $Turret
func _physics_process(delta: float) → void:
acceleration = Vector2.ZERO
get_input()
apply_friction(delta)
calculate_steering(delta)
velocity += acceleration * delta
move_and_collide(velocity * delta)
func apply_friction(_delta: float) → void:
if velocity.length_squared() < 25:
velocity = Vector2.ZERO
var friction_force = velocity * friction
var drag_force = velocity * velocity.length() * drag
if velocity.length() < 100:
friction_force *= 3
acceleration += drag_force + friction_force
func get_input() → void:
var turn = 0
if Input.is_action_just_pressed(“shoot”):
shoot()
if Input.is_action_pressed(“ui_right”):
turn += 1
if Input.is_action_pressed(“ui_left”):
turn -= 1
steer_angle = turn * steering_angle
if Input.is_action_pressed(“accelerate”):
acceleration += transform.x * engine_power
elif Input.is_action_pressed(“brake”):
acceleration -= transform.x * braking
func calculate_steering(delta):
var rear_wheel = position - transform.x * wheel_base / 2.0
var front_wheel = position + transform.x * wheel_base / 2.0
rear_wheel += velocity * delta
front_wheel += velocity.rotated(steer_angle) * delta
var new_heading = (front_wheel - rear_wheel).normalized()
var traction = traction_slow
if velocity.length() > slip_speed:
traction = traction_fast
var d = new_heading.dot(velocity.normalized())
if d > 0:
velocity = velocity.lerp(new_heading * velocity.length(), traction)
if d < 0:
velocity = -new_heading * min(velocity.length(), max_speed_reverse)
rotation = new_heading.angle()
func _process(_delta: float):
var target_dir = global_position.direction_to(get_global_mouse_position())
turret.rotation = target_dir.angle() + PI / 2.0
get_input()
func shoot():
const BULLET = preload(“res://bullet.tscn”)
var new_bullet = BULLET.instantiate()
new_bullet.global_position = %muzzle.global_position
new_bullet.global_rotation = %muzzle.global_rotation
%muzzle.add_child(new_bullet)