Files
Gen_Hack-and-Slash-Roguelit…/Client/Assets/Scripts/Entity/Entity.cs
2025-07-21 16:17:12 +08:00

139 lines
4.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections.Generic;
using AI;
using Base;
using Data;
using UnityEngine;
using UnityEngine.Serialization;
namespace Entity
{
public abstract class Entity:MonoBehaviour,ITick
{
public AIBase aiTree;
public JobBase currentJob;
public AttributesDef runtimeAttributes;
public Vector3 direction;
public bool canSelect = true;
public bool IsChase { set; get; } = true;
public bool PlayerControlled
{
set
{
if (!value)
{
IsChase = true;
}
_isPlayerControlled = value;
}
get => _isPlayerControlled;
}
private bool _isPlayerControlled = false;
private bool _warning = false;
public void Tick()
{
if (PlayerControlled)
{
UpdatePlayerControls();
}
else
{
AutoBehave();
}
}
public virtual void TryAttck()
{
}
/// <summary>
/// 往对应朝向移动moveSpeed*deltaTime的距离
/// </summary>
public virtual void TryMove()
{
transform.position+=direction * (runtimeAttributes.moveSpeed * Time.deltaTime * (IsChase ? 1 : 0.5f));
}
public virtual void OnHit(Entity from)
{
var hit = from.runtimeAttributes.attack - runtimeAttributes.defense;
if (hit < 0)
hit = from.runtimeAttributes.attack / 100;
runtimeAttributes.health -= hit;
currentJob.StopJob();
}
public virtual void SetTarget(Vector3 pos)
{
direction = (pos - transform.position).normalized;
}
public virtual void Kill(float delay = 0)
{
Destroy(gameObject,delay);
}
private void AutoBehave()
{
if (currentJob == null || !currentJob.Running)
{
currentJob = aiTree.GetJob(this);
if (currentJob == null)
{
if (!_warning)
{
Debug.LogWarning($"{GetType().Name}类型的{name}没有分配到任何工作,给行为树末尾添加等待行为,避免由于没有工作导致无意义的反复查找工作导致性能问题");
_warning = true;
}
return;
}
currentJob.StartJob(this);
}
currentJob.Update();
}
private void UpdatePlayerControls()
{
// 获取当前键盘输入状态
var inputDirection = new Vector3();
// 检测 WASD 输入
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
{
inputDirection += Vector3.forward; // 向前移动
}
if (Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow))
{
inputDirection += Vector3.back; // 向后移动
}
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
inputDirection += Vector3.left; // 向左移动
}
if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow))
{
inputDirection += Vector3.right; // 向右移动
}
// 如果有输入方向,则设置目标位置并尝试移动
if (inputDirection != Vector3.zero)
{
// 归一化方向向量,确保对角线移动速度一致
inputDirection = inputDirection.normalized;
// 设置目标位置(假设当前位置为 transform.position
Vector3 targetPosition = transform.position + inputDirection;
// 调用 SetTarget 方法设置目标位置
SetTarget(targetPosition);
// 调用 TryMove 方法处理实际移动逻辑
TryMove();
}
}
}
}