2015-02-24 284 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