Add galilean relativity to shooty enemy

This commit is contained in:
karl 2021-06-07 19:02:13 +02:00
parent 219c8731f5
commit 5f17289426

View File

@ -11,23 +11,26 @@ var bullet_scene = preload("res://Bullet.tscn")
var bullet_velocity = 40.0 var bullet_velocity = 40.0
var target var target
var velocity := Vector3(0.0, 5.0, 10.0)
func _ready(): func _ready():
$ShotTimer.connect("timeout", self, "shoot_bullet") $ShotTimer.connect("timeout", self, "shoot_bullet")
func _process(delta): func _physics_process(delta):
# Project the player's position into the future # Project the player's position into the future
target = _get_future_position( target = _get_future_position(
player.get_center(), player.get_center(),
player.velocity player.velocity - velocity
) )
if target: if target:
var gravity = solar_system.get_gravitation_acceleration(global_transform.origin) var gravity = solar_system.get_gravitation_acceleration(global_transform.origin)
look_at(target, gravity) look_at(target, gravity)
global_transform.origin += velocity * delta
func shoot_bullet(): func shoot_bullet():
if not target: if not target:
@ -38,11 +41,12 @@ func shoot_bullet():
get_tree().get_root().add_child(instance) get_tree().get_root().add_child(instance)
instance.global_transform.origin = global_transform.origin instance.global_transform.origin = global_transform.origin
instance.velocity = (target - global_transform.origin).normalized() * bullet_velocity instance.velocity = velocity + (target - global_transform.origin).normalized() * bullet_velocity
func _get_future_position(position, velocity): func _get_future_position(position, velocity):
# Solution to the quadratic formula gives us the time at which the player would be hit # Solution to the quadratic formula gives us the time at which the player would be hit
# TODO: Take acceleration into account as well!
var a = pow(velocity.x, 2) + pow(velocity.y, 2) + pow(velocity.z, 2) - pow(bullet_velocity, 2) var a = pow(velocity.x, 2) + pow(velocity.y, 2) + pow(velocity.z, 2) - pow(bullet_velocity, 2)
var b = 2 * (velocity.x * (position.x - global_transform.origin.x) var b = 2 * (velocity.x * (position.x - global_transform.origin.x)
+ velocity.y * (position.y - global_transform.origin.y) + velocity.y * (position.y - global_transform.origin.y)