Godot Version
4.2.1
Here is the code:.
extends CharacterBody2D
class_name Player
@onready var animation = $AnimationPlayer
@onready var sprite = $Sprite2D
@export var speed = 200.0
@export var jump_height = -400.0
var gravity = ProjectSettings.get_setting(“physics/2d/default_gravity”)
@export var attacking = false
func _ready():
GameManager.player = self
func _process(delta):
if Input.is_action_just_pressed(“attack”):
attack()
func _physics_process(delta):
if Input.is_action_pressed(“left”):
sprite.scale.x = abs(sprite.scale.x) * -1
$Area2D.scale.x = abs($Area2D.scale.x) * -1
if Input.is_action_pressed(“right”):
sprite.scale.x = abs(sprite.scale.x)
$Area2D.scale.x = abs($Area2D.scale.x)
if not is_on_floor():
velocity.y += gravity * delta
if Input.is_action_just_pressed("jump") and is_on_floor():
velocity.y = jump_height
var direction = Input.get_axis("left", "right")
if direction:
velocity.x = direction * speed
else:
velocity.x = move_toward(velocity.x, 0, speed)
update_animation()
move_and_slide()
if position.y >= 600:
die()
func attack():
var overlapping_objects = $AttackArea.get_overlapping_areas()
for area in overlapping_objects:
if area.get_parent().is_in_group("Enemies"):
area.get_parent().die()
attacking = true
var rand_attack = randi_range(1, 3)
if rand_attack == 1:
animation.play("attack1")
elif rand_attack == 2:
animation.play("attack2")
elif rand_attack == 3:
animation.play("attack3")
func update_animation():
if !attacking:
if velocity.x != 0:
animation.play(“run”)
else:
animation.play(“idle”)
if velocity.y < 0:
animation.play("jump_start")
if velocity.y > 0:
animation.play("jump_end")
func die():
GameManager.respawn_player()
func _on_area_2d_area_shape_entered(area_rid, area, area_shape_index, local_shape_index):
pass # Replace with function body.