This is Player Code:
extends KinematicBody2D
signal died
var velocity = Vector2.ZERO
var gravity = 1000
var maxHorizontalSpeed = 150
var jumpSpeed = 300
var horizontalAcceleration = 2000
var jumpTerminationMultiplier = 4
var hasDoubleJump = false
func _ready():
$HazardArea.connect("area_entered", self, "on_hazard_area_entered")
func _process(delta):
var moveVector = get_movement_vector()
velocity.x += moveVector.x * horizontalAcceleration * delta
if (moveVector.x == 0):
velocity.x = lerp(0, velocity.x, pow(2, -30*delta))
velocity.x = clamp(velocity.x, -maxHorizontalSpeed, maxHorizontalSpeed)
if (moveVector.y < 0 && (is_on_floor() or !$CoyoteTimer.is_stopped() or hasDoubleJump)):
velocity.y = moveVector.y * jumpSpeed
if (!is_on_floor() && $CoyoteTimer.is_stopped()):
hasDoubleJump = false
$CoyoteTimer.stop()
if (moveVector.y < 0 && !Input.is_action_pressed("jump")):
velocity.y += gravity * jumpTerminationMultiplier * delta
else:
velocity.y += gravity * delta
var wasOnFloor = is_on_floor()
velocity = move_and_slide(velocity, Vector2.UP)
if (wasOnFloor && !is_on_floor()):
$CoyoteTimer.start()
if (is_on_floor()):
hasDoubleJump = true
update_animation()
func get_movement_vector():
var moveVector = Vector2.ZERO
moveVector.x = Input.get_action_strength("move_right") - Input.get_action_strength("move_left")
moveVector.y = -1 if Input.is_action_just_pressed("jump") else 0
return moveVector
func update_animation():
var moveVec = get_movement_vector()
if (!is_on_floor()):
$AnimatedSprite.play("jump")
elif (moveVec.x != 0):
$AnimatedSprite.play("run")
else:
$AnimatedSprite.play("idle")
if (moveVec.x !=0):
$AnimatedSprite.flip_h = true if moveVec.x > 0 else false
func on_hazard_area_entered(_area2d):
emit_signal("died")
print("die")
And this is the BaseLevel code:
extends Node
var playerScene = preload("res://scenes/Player.tscn")
var spawnPosition = Vector2.ZERO
var currentPlayerNode = null
func _ready():
spawnPosition = $Player.global_position
register_player($Player)
func register_player(player):
currentPlayerNode = player
currentPlayerNode.connect("died", self, "on_player_died", [], CONNECT_DEFERRED)
func create_player():
var playerInstance = playerScene.instance()
add_child_below_node(playerInstance, currentPlayerNode)
playerInstance.global_position = spawnPosition
register_player(playerInstance)
func on_player_died():
currentPlayerNode.queue_free()
create_player()
Question
Whenever I wrote the code of Baselevel, player is freezing in the air. And Godot tells 'Can’t add child “Player” to Baselevel, already has a parent “Baselevel” '. I How can I fix this? Thank you. I forgot to mention, it is Godot3.3