简体   繁体   English

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

[英]2D rotation and collision detection in Unity3d with C# Script

I have a game object, a yellow circle that shown in this picture as my player object and the red one is the child of my player object. 我有一个游戏对象,一个黄色圆圈(在此图片中显示为我的玩家对象),红色圆圈是我的玩家对象的孩子。

Then If i press spacebar key once, it will rotate by -90 degrees like this 然后,如果我按空格键一次,它将像这样旋转-90度

The problem is when i press the spacebar key twice, my player rotating perfectly but it stuck and continue vibrating hitting the pink block.My question is, how can i modify my script to make the player know if it just only can rotate once and prevent the player from rotating again if i press the spacebar key because of the pink block will barrier it rotation. 问题是当我按两次空格键时,播放器旋转完美,但卡住并继续振动并击中粉红色块。我的问题是,如何修改脚本以使播放器知道它只能旋转一次并防止如果由于粉红色块而我按空格键,则播放器无法再次旋转,将阻止旋转。

Here is my Player rotator script. 这是我的Player旋转脚本。

 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)); } 

Sorry if i not good in english. 对不起,如果我英语不好。 Every comments and help are very appreciated. 每个意见和帮助都非常感谢。

If you want your coroutine to run just once you can modify it like this 如果您希望协程仅运行一次,则可以像这样修改它

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));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM