使用C#脚本在Unity3d中进行2D旋转和碰撞检测



我有一个游戏对象,图中显示的黄色圆圈是我的玩家对象,红色圆圈是我玩家对象的子对象。

然后,如果我按下空格键一次,它会像一样旋转-90度

问题是,当我按下空格键两次时,我的播放器旋转得很好,但它卡住了,并继续振动,击中了粉红色的方块。我的问题是,如果我按下空格键,我如何修改我的脚本,让玩家知道它是否只能旋转一次,并防止玩家再次旋转,因为粉色块会阻碍它的旋转。

这是我的播放器旋转器脚本。

public GameObject objToRotate;
private bool rotating = false;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.Space)) 
{
StartRotation ();
}


}
private IEnumerator Rotate(Vector3 angles, float duration)
{
rotating = true;
Quaternion startRotation = objToRotate.transform.rotation;
Quaternion endRotation = Quaternion.Euler (angles) * startRotation;
for (float t = 0; t < duration; t += Time.deltaTime) {
objToRotate.transform.rotation = Quaternion.Lerp (startRotation, endRotation, t / duration);
yield return null;
}
objToRotate.transform.rotation = endRotation;
rotating = false;
}
public void StartRotation()
{
if (!rotating)
StartCoroutine (Rotate (new Vector3 (0, 0, -90), 1.1f));
}

对不起,如果我英语不好。我们非常感谢您的每一条评论和帮助。

如果你想让你的协同程序只运行一次,你可以像这个一样修改它

public GameObject objToRotate;
private bool rotating = false;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && !rotating)
{
StartRotation();
}

}
private IEnumerator Rotate(Vector3 angles, float duration)
{
rotating = true;
Quaternion startRotation = objToRotate.transform.rotation;
Quaternion endRotation = Quaternion.Euler(angles) * startRotation;
for (float t = 0; t < duration; t += Time.deltaTime)
{
objToRotate.transform.rotation = Quaternion.Lerp(startRotation, endRotation, t / duration);
yield return null;
}
objToRotate.transform.rotation = endRotation;
}
public void StartRotation()
{
if (!rotating)
StartCoroutine(Rotate(new Vector3(0, 0, -90), 1.1f));
}

最新更新