2015-02-24 337 views
1

我試圖通過按鍵輸入(箭頭向下或向上)來獲取精靈旋轉。 重點是解除箭頭(精靈)選擇角度。它就像一個高爾夫遊戲系統,實際上。Unity - Sprite旋轉+獲取角度

到目前爲止,我嘗試:

void Update() { 

    if (Input.GetKey(KeyCode.UpArrow)){ 
     transform.Rotate (Vector3.forward * -2); } 
if (Input.GetKey(KeyCode.DownArrow)){ 
    transform.Rotate (Vector3.forward * +2); } 

}

我需要的角度,因爲它會涉及到一個「鏡頭」部分我接下來將做什麼。我的觀點是上下鍵設置正確的角度。

我可以用我的代碼移動「箭頭」的精靈,但我不能設置最大角度(90°),最小值(0),並獲得在鏡頭^^

回答

1

很難回答的使用回答角而不只是簡單地給你代碼。此代碼的工作原理是假設你的角色的正向矢量實際上是它的(在2D精靈遊戲常見)向右向量,以便在其他方向拍攝,旋轉你的對象y軸的180

float minRotation = 0f; 
float maxRotation = 90f; 
float rotationSpeed = 40f; //degrees per second 

//get current rotation, seeing as you're making a sprite game 
// i'm assuming camera facing forward along positive z axis 
Vector3 currentEuler = transform.rotation.eulerAngles; 
float rotation = currentEuler.z; 

//increment rotation via inputs 
if (Input.GetKey(KeyCode.UpArrow)){ 
    rotation += rotationSpeed * Time.deltaTime; 
} 
else if (Input.GetKey(KeyCode.DownArrow)){ 
    rotation -= rotationSpeed * Time.deltaTime; 
} 

//clamp rotation to your min/max 
rotation = Mathf.Clamp(rotation, minRotation, maxRotation); 

//set rotation back onto transform 
transform.rotation = Quaternion.Euler(new Vector3(currentEuler.x, currentEuler.y, rotation)); 

如果你犯了個高爾夫球場遊戲中,您將球的速度設置爲transform.right * shotPower

+0

非常感謝!現在我唯一的問題是精靈顯示倒置。 u.u現在我必須處理角色變換的方向(也可以面向相反的方向 - 角色可以左右移動!)。但我可以處理這個,我確定^ _ ^非常感謝! – pumpkinChan 2015-02-25 12:53:22