Godot - вызов экземпляра сцены для определенной ошибки позиции - PullRequest
0 голосов
/ 27 марта 2020

Я пытался создать сцену, похожую на пулю для платформерного шутера в Годо. Я создал сцену с узлом root, являющимся Area2D, со столкновением и уведомлением о видимости. Код в этом узле root выглядит следующим образом:

extends Area2D

export var bullet_speed = 400
var motion = Vector2()

func start():
    position = Vector2()
    pass

func _physics_process(delta):
    motion.x = bullet_speed * delta
    translate(motion)


func _on_VisibilityNotifier_screen_exited():
    queue_free()
    pass # Replace with function body.

Тогда у меня есть сцена, в которой есть сцена игрока. В сцене игрока узел root представляет собой KinematicBody2D, A Collision Shape и Position2D без изменения имени

Скрипт игрока (сокращенно) имеет дельту физического процесса со следующими командами:

const bulletlaunch = preload("res://Sprites/Gun Animation/Bullet.tscn") ##Declared the bullet scene

func _physics_process(delta):
    Engine.target_fps = 60
    #Playable when NOT dead
    if is_dead == false:
        var x_input = Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left")

        hud_score_display.text = String(GlobalScore.score)
        score_display.text = String(GlobalScore.score)
        heart_hud.value = health

        if health >= 75 && health <= 100:
            heart_hud.tint_progress = Color.green
        if health >= 50 && health <= 74:
            heart_hud.tint_progress = Color.orange
        if health >= 25 && health <= 49:
            heart_hud.tint_progress = Color.red

        if x_input != 0:
            if x_input == -1:
                if playing_health_damage == false:
                    character.flip_h = true
                    character.play("Idle")
            if x_input == 1:
                if playing_health_damage == false:
                    character.flip_h = false
                    character.play("Idle")
            motion.x += x_input * acceleration * delta
            motion.x = clamp(motion.x, -max_speed, max_speed)
        else:
            if playing_health_damage == false:
                motion.x = lerp(motion.x, 0, air_resistance)
                character.play("Idle")

        motion.y += gravity * delta
        if is_on_floor():
            if x_input == 0:
                motion.x = lerp(motion.x, 0, friction)
            if Input.is_action_just_pressed("ui_up"):
                motion.y = -jump_force
                small_jump_sound.play()

        if Input.is_action_just_pressed("ui_action"): ##The place where I have the error
            var bulletinstance = bulletlaunch.instance()
            get_parent().add_child(bulletinstance)
            bulletinstance.position = $Position2D.global_position

        motion = move_and_slide(motion, Vector2.UP)
        pass

Однако, когда я нажимаю клавишу ui_action, я получаю эту ошибку

Invalid get index 'global_position' (on base: 'null instance').

Что я на самом деле не понимаю ..

Что Я пытался:

  1. Изменение global_position для положения в обеих из них и выполнение всех комбинаций
  2. Найти другую Position2D-подобную замену, но я не могу найти ничего подобного что
  3. использует print (Playershootpos.position) в операторе if ui_action, но, похоже, я получаю ту же ошибку. Странно.

Другой вопрос:

Есть ли какие-нибудь замены для узла Position2D? И в чем проблема?

...