control:界面层,点击start进入map
extends Control
@onready var start = $Button
# Called when the node enters the scene tree for the first time.
func _ready():
start.connect("button_down", self._on_pressed_)
pass # Replace with function body.
func _on_pressed_():
get_tree().change_scene_to_file("res://map.tscn")
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
pass
map:二维的地图,npc发现玩家开始追逐,追逐成功进入attack地图,注意要放两个area2D检测,一个是检测是否追逐,一个是检测是否进入attack地图 (attack是一个横板单挑地图)
extends Node2D
# Called when the node enters the scene tree for the first time.
func _ready():
pass # Replace with function body.
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
if Global.is_attack == true:
print("move to attack...")
get_tree().change_scene_to_file("res://attack.tscn")
pass
NPC :Globa的位置就是玩家实时更新的位置
extends CharacterBody2D
const SPEED = 8000.0
var is_atttack
@onready var timer = $Timer
var dir = Vector2.RIGHT
var move = false
func _physics_process(delta):
if is_atttack:
velocity = (Global.player_pos - position).normalized() * SPEED * delta
move_and_slide()
return
if timer.is_stopped():
return
if !timer:
timer.set_wait_time(random_something([1, 0.5, 0]))
timer.start()
if move:
#dir = random_something([Vector2.RIGHT, Vector2.LEFT, Vector2.UP, Vector2.DOWN])
velocity = dir * SPEED * delta
move_and_slide()
func _on_area_2d_body_entered(body):
if body.is_in_group("player"): #没有这一行,开局就会和map碰撞,直接卡死
is_atttack= true
pass
func _on_area_2d_body_exited(body):
is_atttack= false
pass # Replace with function body.
func random_something(arr): #获取一个随机数
arr.shuffle()
return arr.front()
func _on_timer_timeout():
move = !move
dir = random_something([Vector2.RIGHT, Vector2.LEFT, Vector2.UP, Vector2.DOWN])
pass # Replace with function body.
func _on_attack_body_entered(body):
if body.is_in_group("player"): #这一行至关重要,我没加,每次都是attcak
Global.is_attack = true
pass # Replace with function body.