簡體   English   中英

如何根據鼠標位置旋轉對象的位置?

[英]How to rotate the position of an object based on mouse position?

我現在正在使用此代碼將坦克炮塔對象向鼠標位置旋轉:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Physics.Raycast(ray, out hit, range);
Vector3 dir = hit.point - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = lookRotation.eulerAngles;
transform.rotation = Quaternion.Euler(0f, rotation.y, 0f);

即使射線沒有擊中任何物體(將鼠標指向沒有引發任何物體的位置)(擊中為false),有沒有辦法產生旋轉? 還有沒有更好的方法來提供更好的解決方案?

謝謝。

基本上,我只是獲得鼠標在屏幕上的位置,將其與目標對象進行比較,將其轉換為度數,然后圍繞所需的軸旋轉對象(Y為topDown 3D空間,Z為2D)。

void RotateTowards()
    {
        var mouse = Input.mousePosition;
        var screenPoint = Camera.main.WorldToScreenPoint(tankTransform.localPosition);
        var offset = new Vector2(mouse.x - screenPoint.x, mouse.y - screenPoint.y);
        var angle = Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0, angle, 0);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM