Unity - Sprite旋转+获取角度

时间:2015-02-24 19:28:49

标签: c# unity3d

我试图通过键输入(箭头向下或向上)来获得精灵旋转。 要点是抬起箭头(精灵)来选择角度。实际上它就像是一个高尔夫比赛系统。

到目前为止我试过了:

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 个答案:

答案 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