1.實現劍跟隨飛行方向旋轉
修改劍的預制體使劍的朝向對準右x軸
Sword_Skill_Contorl腳本:
? ? private void Update()
{
transform.right = rb.velocity;//時刻更新位置
}
2.實現劍插入地面或者敵人
修改預制體為觸發器
Sword_Skill_Contorl腳本:
? ? private bool canRotate=true;
? ? private void Update()
{
if(canRotate)//可以旋轉才能設置速度
{
transform.right = rb.velocity;
? ? ? ? }
? ? ? ?
}
? ? private void OnTriggerEnter2D(Collider2D collision)
{
canRotate = false;//不能旋轉
cd.enabled = false;//關閉碰撞器
? ? ? ? rb.isKinematic = true;//設置為Kinematic,這是一個運動學狀態
rb.constraints = RigidbodyConstraints2D.FreezeAll;//鎖定xyz
? ? ? ? transform.parent = collision.transform;//將劍設置為碰撞到物體的子對象
}
演示:
3.玩家只能持有1把劍即當一把劍被投擲時不能進入瞄準狀態
Player腳本:
? ? public GameObject sword { get; private set; }//劍的對象
? ? public void AssignNewSword(GameObject _newSword)//分配
{
sword = _newSword;
}
? ? public void clearTheSword()//銷毀
{
Destroy(sword);
}
Sword_Skill腳本:
player.AssignNewSword(newSword);//在CreatSword()中調用
PlayerGroundedState腳本:
? ? ? ? if(Input.GetKeyDown(KeyCode.Mouse1)&&!_Player.sword)//不持有劍才能按下鼠標右鍵
{
_PlayerStateMachine.ChangeState(_Player.AimSword);
}
4.玩家再此按下鼠標右鍵時可以回收劍
Sword_Skill_Control腳本:
? ? [SerializeField] private float returnSpeed=12f;//返回的速度
? ? private bool isReturning;//是否返回
? ? public void SetupSword(Vector2 _dir,float _gravityScale,Player _player)//傳入player,作為返回目標,從Sword_Skill腳本中傳入
{
rb.velocity = _dir;
rb.gravityScale = _gravityScale;
? ? ? ? player = _player;
? ? ? ? anim.SetBool("rotation", true);//設置旋轉動畫
}
? ? public void ReturnSword()
{
rb.isKinematic=false;
transform.parent = null;//取消原父對象
? ? ? ? isReturning = true;//開始返回
}
? ? private void Update()
{
if(canRotate)
{
transform.right = rb.velocity;
? ? ? ? }
? ? ? ?if(isReturning)
{
transform.position = Vector2.MoveTowards(transform.position, player.transform.position, returnSpeed*Time.deltaTime);//向玩家移動
? ? ? ? ? ? if(Vector2.Distance(transform.position, player.transform.position)<1)//距離小于1時銷毀
{
player.clearTheSword();
}
}
}
PlayerGroundedState腳本:
? ? private bool HasNoSword()//是否投擲出劍
{
if (!_Player.sword)//未投擲可以進入瞄準
{
return true;
}
? ? ? ? _Player.sword.GetComponent<Sword_Skill_Control>().ReturnSword();//已經投擲則調用返回函數
return false;
}
? ? ? ? if(Input.GetKeyDown(KeyCode.Mouse1)&&HasNoSword())//Update中
{
_PlayerStateMachine.ChangeState(_Player.AimSword);
}
演示: