创建接口
由于所有可互动的物体都会有一个共通的属性,即"互动"的处理。因此,新建一个接口,让所有可互动的物体都实现这个接口内的互动处理方法
新建接口

创建一个处理互动逻辑的抽象方法
c#
public interface IInteractable
{
void TriggerAction();
}
创建处理宝箱交互逻辑的脚本

在宝箱脚本内实现这个接口,并重写接口内的方法。之后宝箱互动逻辑都在这个方法内实现
c#
public class Chest : MonoBehaviour, IInteractable
{
public void TriggerAction()
{
}
}
按键互动与实现接口
在InputSystem
中添加互动按钮的输入

在OnEnable()
方法中追加,当互动按键按下时,执行按键触发后的一系列处理工作
c#
private void OnEnable()
{
InputSystem.onActionChange += OnActionChange;
playerInput.Gameplay.Interact.started += OnInteract;
}
只有当可以互动的时候进行处理
c#
private void OnInteract(InputAction.CallbackContext context)
{
if (canPress)
{
}
}
这时候就需要获取可互动目标实体,在OnTriggerStay2D()
方法中,能够直接读取到目标实体。那么就获取这个目标实体,并传入到全局变量中
c#
private IInteractable targerItem;
private void OnTriggerStay2D(Collider2D collision)
{
// 如果碰撞体标签为可互动的
if (collision.CompareTag("Interactable"))
{
canPress = true;
// 获得可互动的目标实体
targerItem = collision.GetComponent<IInteractable>();
}
}
接着,在OnInteract()
方法中,操作这个可互动目标实体,调用接口的抽象类
c#
private void OnInteract(InputAction.CallbackContext context)
{
if (canPress)
{
targerItem.TriggerAction();
}
}
宝箱互动基础逻辑
宝箱的互动会有关闭状态的图片、开启状态的图片以及可互动物体的互动状态
c#
private SpriteRenderer spriteRenderer;
public Sprite openSprite;
public Sprite closeSprite;
// 互动完毕标志,记录已互动的状态
public bool isDone;
Awake()
方法中初始化宝箱实体,OnEnable()
方法中,判断是否结束了互动,进行不同的图片状态赋值
c#
private void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
}
private void OnEnable()
{
spriteRenderer.sprite = isDone ? openSprite : closeSprite;
}
按键互动中,如果宝箱没有被互动的话,就打开宝箱,并赋予打开宝箱的图片。在互动结束,一定要把互动状态调整为True
,标志为不可再互动
c#
public void TriggerAction()
{
if (!isDone)
{
OpenChest();
}
}
private void OpenChest()
{
spriteRenderer.sprite = openSprite;
isDone = true;
// 互动完后,将宝箱的标签标记为默认,这样后面接触到已交互的宝箱就不会弹出按键提示了
this.gameObject.tag = "Untagged";
}
在宝箱实体中,绑定Chest
脚本,赋予宝箱对应的图片

交互音效
为宝箱实体绑定上Audio Definition
脚本的组件,Play Audio Event
选择FX,Audio Clip
选择对应的声音音效

在IInteractable接口中,创建新的抽象方法PlayFXAudio()
,用于播放可互动实体互动时候的音效
c#
public interface IInteractable
{
void TriggerAction();
void PlayFXAudio();
}
在宝箱实体类中,实现此方法,调用Audio Definition
c#
public void PlayFXAudio()
{
GetComponent<AudioDefinition>()?.PlayAudioClip();
}
最后在ButtonSign的脚本中,OnInteract()方法追加调用接口的PlayFXAudio()
抽象方法,即可实现触发音效
c#
private void OnInteract(InputAction.CallbackContext context)
{
if (canPress)
{
targerItem.TriggerAction();
// 播放音效
targerItem.PlayFXAudio();
}
}
传送门的交互
给传送门创建Collider 2D

绑定脚本

实现IInteractable
接口,即可完成
c#
public class TeleportPoint : MonoBehaviour, IInteractable
{
// 坐标点
public Vector3 positionToGo;
public void PlayFXAudio()
{
throw new System.NotImplementedException();
}
public void TriggerAction()
{
throw new System.NotImplementedException();
}
}