[英]Unity 2D Rotating Enemy Towards Player
我是 Unity 新手,正在開發一款 2D 自上而下的射擊游戲。 我已經為敵人編寫了一個腳本,當他們有視線時,他們會旋轉到玩家身邊。 我現在要做的是讓當玩家進入敵人的視線時,敵人不會立即面對玩家,而是快速旋轉以面對他們。 我當前執行此操作的代碼位於腳本的 while 循環中,當玩家進入敵人的視線時會導致 Unity 崩潰,知道我做錯了什么嗎? 順便說一句,我的腳本在沒有 while 循環及其內容的情況下工作正常。
'''C#
private void FixedUpdate()
{
Vector2 playerDir = playerLocation.position - this.transform.position;
float angle = (Mathf.Atan2(playerDir.y, playerDir.x) * Mathf.Rad2Deg);
if (canSeePlayer())
{
while (angle - rb.rotation < 10f || angle-rb.rotation > 10f)
{
rb.MoveRotation(rb.rotation + 1);
}
rb.MoveRotation(angle - 90);
}
}
private bool canSeePlayer()
{
RaycastHit2D hit = Physics2D.Raycast(this.transform.position, playerLocation.position - this.transform.position);
Debug.DrawRay(this.transform.position, playerLocation.position - this.transform.position);
Debug.Log(hit.collider.gameObject);
if (hit.collider.gameObject.CompareTag("Player"))
{
return true;
}
else
{
return false;
}
'''
許多物理組件適用於固定更新,許多方法不會立即進行更改
例如:您可以使用此代碼進行測試
var rotation = Rigidbody.rotation; // before
Rigidbody.MoveRotation(5);
var newRotation = Rigidbody.rotation; // after
在您調用 rigibody.moveRotation (在第 2 行)之后,旋轉仍然等於 newRotation 並且您將看到下一個固定更新的更新,說明 Unity 崩潰的原因(因為無限循環,您的旋轉不更新)
我相信 Mathf.Lerp 是您正在尋找的東西,它允許平滑值的變化而不會超出它們。 在您的 FixedUpdate 中試試這個:
Vector2 playerDir = playerLocation.position - this.transform.position;
float angle = (Mathf.Atan2(playerDir.y, playerDir.x) * Mathf.Rad2Deg);
float rotationSpeed = 1f;
rb.rotation = Mathf.Lerp(rb.rotation, angle, rotationSpeed);
當然,歡迎您根據自己的喜好調整rotationSpeed
,並將其提取到可在編輯器中編輯的 class 變量中。
關於您的游戲凍結,請注意您的while
退出條件沒有很好地定義:
while (angle - rb.rotation < 10f || angle-rb.rotation > 10f)
請注意,如果您從比rb.rotation
小 10 的angle
開始,您最終會在循環中進一步增加rb.rotation
,從而創建一個沒有退出條件的無限循環。
示例: angle = 0
和rb.rotation = 15f
0. angle - rb.rotation = -15 (less than 10f) => execute loop => rb.rotation++
1. angle - rb.rotation = -16 (less than 10f) => execute loop => rb.rotation++
2. angle - rb.rotation = -17 (less than 10f) => execute loop => rb.rotation++
3. ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.