【问题标题】:2D rotation and collision detection in Unity3d with C# Script使用 C# 脚本在 Unity3d 中进行 2D 旋转和碰撞检测
【发布时间】:2019-04-21 11:14:22
【问题描述】:

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

然后如果我按一次空格键,它将旋转-90度like this

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

这是我的 Player rotator 脚本。

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

对不起,如果我的英语不好。非常感谢每一个 cmets 和帮助。

【问题讨论】:

    标签: c# unity3d rotation 2d collision


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多