- Edited
Hello, I'm trying to create a homing missile that automatically locks on the closest possible target and flies towards it. I managed to get it to work by following the instructions in the "Godot Recipes: Homing Missiles" tutorial by KidsCanCode. However, I'm not happy with the way the missile flies. It acts more like it's attracted towards the target via gravity rather than steering towards it. When I shoot the missile away from the target, it flies straight, decelerates, then flips around and accelerates towards the target. That's not how missiles fly, at least not in atmosphere. However, I can't figure out how to change it so the missile keeps its speed and actually steers towards the target and I couldn't find any other tutorial. Can anyone help me?
Here's the code for the missile. I removed some parts not related to the movement to make it shorter. If required I can post the entire script.
extends Area2D
export (int) var damage = 10
export (int) var speed = 500
export (float) var recoil = 0 #50
export (float) var steer_force = 15.0
export (int) var step_size
export (PackedScene) var explosion
export (PackedScene) var splash_damage
onready var life_time = $LifeTime
onready var raycast = $FindTargets
var target : Node2D = null
var direction = Vector2.ZERO
var current_step : int
var velocity = Vector2.ZERO
var acceleration = Vector2.ZERO
func start(_transform):
global_transform = _transform
velocity = transform.x * speed
func _physics_process(delta):
if current_step < (360/step_size):
target = get_target(detect_targets())
acceleration = seek()
velocity += acceleration * delta
velocity = velocity.clamped(speed)
rotation = velocity.angle()
position += velocity * delta * 100 # *100 not in original code but without it missile is slow af
func _on_HomingMissile_body_entered(body):
#damage and explosion code, removed to shorten post, is already long enough
func _on_LifeTime_timeout():
queue_free()
func detect_targets() -> Array:
#code to detect all possible targets, removed to shorten post
func get_target(target_array) -> Node2D:
#code to find closest target, removed to shorten post
func seek():
var steer = Vector2.ZERO
if target:
var desired = (target.position - position).normalized() * speed
steer = (desired - velocity).normalized() * steer_force
return steer