如何在 Unity2d 中使用 C# 脚本旋转对象?

How To Rotate Objects Using C# Script In Unity2d?

所以我尝试将我的硬币对象旋转到 0z 如果 Y 高于 0.17f 并且如果它不是将旋转回 90z ,第一个 if 语句工作正常但另一个继续旋转我的硬币并且我不不知道为什么...?我对 Unity 和 C# Lang 完全陌生!

无论如何这是我的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class CoinScript : MonoBehaviour
{
    public GameObject coin;
 
    bool isRotated = false;
 
    // Update is called once per frame
    void FixedUpdate()
    {
        if (coin.transform.position.y > 0.17f && coin.transform.rotation.z >= 0f && !isRotated)
        {
           
            coin.transform.Rotate(coin.transform.rotation.x,coin.transform.rotation.y,-1f );
 
            if (coin.transform.rotation.z <= 0f)
            {
                isRotated = true;
            }
 
        }else if (coin.transform.position.y < 0.17f && coin.transform.rotation.z <= 90f && isRotated)
        {
           
            coin.transform.Rotate(coin.transform.rotation.x,coin.transform.rotation.y,1f);
           
            if (coin.transform.rotation.z >= 90f)
            {
                isRotated = false;
            }
           
        }
    }
}

Transform.rotation is a Quaternion!

顾名思义一个Quaternion(另见维基百科->四元数不是三个而是四个个组件xyzw。所有这些都在 -1+1 范围内移动。除非你真的知道你在做什么,否则你 永远不会 直接触摸这些组件。


如果我对你的理解正确的话,你宁愿做一些事情,例如

public class CoinScript : MonoBehaviour
{
    public Transform coin;
    public float anglePerSecond = 90;
 
    private void FixedUpdate()
    {
        var targetRotation = coin.position.y > 0.17f ? Quaternion.identity : Quaternion.Euler(0, 0, 90);

        coin.rotation = Quaternion.RotateTowards(coin.rotation, targetRotation, anglePerSecond * Time.deltaTime);
    }
}