![](/img/trans.png)
[英]Why does my camera clip into the player object when rotating around it?
[英]How to make my player face cursor even when I am rotating around the player?
我想讓玩家在 3d 游戲中面對 cursor,為此我向玩家添加了這段代碼
void Update()
{
Vector3 objectPos = cam.WorldToScreenPoint(transform.position);
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 90- angle, 0));
}
這在相機面向玩家時有效,但當我轉動玩家時它不再跟隨 cursor。 當我停下來時(例如,相機現在在播放器后面或左側),播放器旋轉面向錯誤的 position。
您需要將相機旋轉添加到最終旋轉的計算中。
[SerializeField] Camera cam;
[SerializeField] Vector3 rotOffset;
void Update()
{
Vector3 objectPos = cam.WorldToScreenPoint(transform.position);
Vector2 mousePos = Input.mousePosition;
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
transform.rotation = cam.transform.rotation * Quaternion.Euler(new Vector3(0, 0, angle)) * Quaternion.Euler(rotOffset);
}
我已將您的初始旋轉偏移量提取到一個單獨的變量中。 您可能需要使用它來重新獲得正確的方向,並可能更改angle
影響的軸。 另請注意,四元數乘法考慮了操作順序。 只有在旋轉完全錯誤時才切換它。
解決方案是我需要將 y 軸的攝像機角度添加到 90 度偏移,如下所示:
transform.rotation = Quaternion.Euler(new Vector3(0, (cam.transform.eulerAngles.y+90)-angle, 0)) ;
現在播放器總是面向 cursor 即使我轉身播放器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.