横版2D游戏:类银河恶魔城开发笔记四

📅 2026/8/4 9:50:10
横版2D游戏:类银河恶魔城开发笔记四
EnemyTer ——角色进入领地触发器当角色进入怪物领地时怪物会进入追击状态当玩家离开怪物领地并且距离较远时会切换回巡逻状态。触发器代码public void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.tag Player) { enemyBase.FindPlayer(collision.gameObject); } } public void OnTriggerExit2D(Collider2D collision) { if (collision.gameObject.tag Player) { enemyBase.PlayerOut(); } }与EnemyBase的协作public virtual void FindPlayer(GameObject mainPlayer) { if(currentState ! EnemyState.Death) { player mainPlayer; ChangeCurrentState(EnemyState.Pursuit); } } public virtual void PlayerOut() { if(currentState ! EnemyState.Death) { ChangeCurrentState(EnemyState.Patrol); } }EnemyAttackBox——敌人攻击判定框逻辑与PlayerAttackBox相同。Start()void Start() { Destroy(gameObject, destroyTime); }利用Start控制攻击框的生命周期一定时间后自动销毁。触发器碰撞检测与伤害传递void OnTriggerEnter2D(Collider2D other) { if (other.CompareTag(Player)) { PlayerScript player other.GetComponentPlayerScript(); player.GetHit(damage); } }当判定框内的对象标签是Player时将应该造成的伤害传递给Player中的GetHit方法。DamageNum——伤害数字自动销毁脚本内只有延时自毁的功能。只负责控制伤害数字的生命周期并在一定时间后销毁。在EnemyBase中的调用GameObject go Instantiate(damageNum, damageNumPoint.position, damageNumPoint.rotation, hpCanves.transform); go.transform.localScale damageNumPoint.localScale; go.GetComponentText().text damage.ToString();实例化伤害数字预制体挂载到UI Canvas下。设置缩放匹配预设大小。通过GetComponentText.text获取伤害数值填入。CameraCinema——视差滚动背景只负责实现视差滚动效果当摄像机移动时背景层以不同于摄像机的速度跟随。Vector3 amount2Move transform.position - lastPos; Vector3 offect new Vector3(amount2Move.x * offectSpeed.x, amount2Move.y * offectSpeed.y, 0); backGround.position offect; lastPos transform.position;通过amount2Move存储摄像机当前帧和上一帧的位移差利用offect按比例缩放唯一形成远景和近景效果。BackgroundMap——无限循环背景当摄像机移动到某一位置时背景块会自动平移到另一端形成无限延伸的视觉。初始化宽度void Start() { mapWidth GetComponentSpriteRenderer().bounds.size.x; totalWidth mapWidth * mapNum; }获取单个背景图在世界空间中的实际宽度计算总宽度。边界检测与平移void Update() { Vector3 tempPosition transform.position; if (mainCamera.transform.position.x transform.position.x totalWidth / 2) { tempPosition.x totalWidth; transform.position tempPosition; } else if (mainCamera.transform.position.x transform.position.x - totalWidth / 2) { tempPosition.x - totalWidth; transform.position tempPosition; } }当摄像机x坐标背景中点总宽度一半的时候将背景带向右平移整个宽度小于就反之。SoundManger——音频管理单例采用单例模式负责BGM和SFX的播放。单例模式实现[HideInInspector] public static SoundManger instance; private void Awake() { if (instance null) { instance this; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } }单例初始化必须在Awake中完成因为Awake比Start先执行确保其他脚本在Start中访问instance时已经可用。通过DontDestroyOnload()使当前对象在切换场景时不被销毁保持音频播放的连续性。