Unity2D看向滑鼠方向
阿新 • • 發佈:2018-12-13
Quaternion turntodirection(Vector3 targetpt, Vector3 originalPt) { float y = targetpt.y - originalPt.y; float h = targetpt.x - originalPt.x; float aa = Mathf.Atan2(y, h) * (-180) / 3.1415926f + 90; // 此處注意的是: Mathf.Atan2(y軸座標值,x軸座標值); 是自y軸開始的角度(即順時針方向),如果是Mathf.Atan2(x,y),則是自x軸開始的角度(即逆時針方向) //=================== float angle = Mathf.Atan2(vDir.x, vDir.y) * Mathf.Rad2Deg;//用這種方式更高效! //==================== Quaternion angle = Quaternion.Euler(0f, 0f, -aa); Debug.Log("angle" + aa); return angle; //curRole.transform.rotation = angle; }
Update函式中
Vector2 mousePositionOnScreen = Input.mousePosition; //讓場景中的Z=滑鼠座標的Z
Vector2 mousePositionInWorld = Camera.main.ScreenToWorldPoint(mousePositionOnScreen);
s_head.rotation = turntodirection(mousePositionInWorld, s_head.position);