Godot Version
<stabel4.2>
Question
<Im making 2d enemy jump and land on player position. Right now, with my code, enemy can successfully jump and land on player position. However, when I added hang time, enemy’s landing position is misaligned. I would appreciate if you could help me solve the problem.
States.JUMP:
if state != States.JUMP:
return
if jump_state:
$AnimationPlayer.play("jump")
calculate_velocity()
jump_state = false
if !is_on_floor():
if velocity.y > 0 and velocity.y < 5:
hang_time -= delta
if hang_time <= 0:
velocity.y = min(velocity.y, 0)
else:
velocity.y += gravity * delta
move_and_slide()
func calculate_velocity():
print("JUMP")
var target_position = player.global_position
var start_position = self.global_position
var distance_x = target_position.x - start_position.x
var distance_y = target_position.y - start_position.y
var total_distance = sqrt(distance_x * distance_x + distance_y * distance_y)
if total_distance > max_distance:
var new_target_pos = max_distance / total_distance
distance_x *= new_target_pos
distance_y *= new_target_pos
var velocity_x = distance_x / time_to_reach
var velocity_y = (distance_y - 0.5 * gravity * time_to_reach * time_to_reach) / time_to_reach
velocity = Vector2(velocity_x, velocity_y)