日志2025.1.30
日志2025.1.30
1.简略地做了一下交互系统
public class Interactable : MonoBehaviour
{
private MeshRenderer renderer;
private Material defaultMaterial;
public Material highlightMaterial;
private void Awake()
{
renderer = GetComponentInChildren<MeshRenderer>();
defaultMaterial = renderer.material;
}
public virtual void Interaction()
{
Debug.Log("www");
}
public void HightLightActive(bool active)
{
if (active)
{
renderer.material = highlightMaterial;
}
else
{
renderer.material = defaultMaterial;
}
}
protected virtual void OnTriggerEnter(Collider other)
{
PlayerInteraction playerInteraction = other.GetComponent<PlayerInteraction>();
if (playerInteraction == null) return;
playerInteraction.interactables.Add(this);
playerInteraction.ChangeClosestInteractable();
}
protected virtual void OnTriggerExit(Collider other)
{
PlayerInteraction playerInteraction = other.GetComponent<PlayerInteraction>();
if (playerInteraction == null) return;
playerInteraction.interactables.Remove(this);
playerInteraction.ChangeClosestInteractable();
}
}
public class PlayerInteraction : MonoBehaviour
{
public List<Interactable> interactables;
private Interactable closestInteractable;
private Player player;
private void Awake()
{
player = GetComponent<Player>();
PlayerControls controls = player.controls;
controls.Character.Interaction.performed += context => InteractWithClosest();
}
private void InteractWithClosest()
{
closestInteractable?.Interaction();
}
//找到最近的可互动物,并将其高光
public void ChangeClosestInteractable()
{
closestInteractable?.HightLightActive(false);
closestInteractable = null;
float closestDistance = float.MaxValue;
foreach (Interactable interactable in interactables)
{
float distance = Vector3.Distance(transform.position, interactable.transform.position);
if (distance < closestDistance) {
closestDistance = distance;
closestInteractable = interactable;
}
}
closestInteractable?.HightLightActive(true);
}
}
2.将该交互系统用于拾取武器
public class Pickup_Weapon : Interactable
{
private PlayerWeaponController playerWeaponController;
[SerializeField] private Weapon_Data weaponData;
public override void Interaction()
{
base.Interaction();
playerWeaponController.PickUpWeapon(weaponData);
}
protected override void OnTriggerEnter(Collider other)
{
base.OnTriggerEnter(other);
if (playerWeaponController == null)
{
playerWeaponController = other.GetComponent<PlayerWeaponController>();
}
}
protected override void OnTriggerExit(Collider other)
{
base.OnTriggerExit(other);
}
}