如何使一个对象基于另一个对象旋转?

时间:2019-05-12 18:22:47

标签: c# unity3d

我有一个齿轮,用户可以转动旋转吊桥。目前,齿轮和吊桥以相同的速度旋转,就像这样:https://gyazo.com/14426947599095c30ace94a046e9ca21

这是我当前的代码:

[SerializeField] private Rigidbody2D thingToRotate;
    void OnMouseDrag()
    {
        Vector3 mousePosition = Input.mousePosition;
        mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);

        Vector2 direction = new Vector2(
            mousePosition.x - transform.position.x,
            mousePosition.y - transform.position.y
         );

        transform.right = direction;
        thingToRotate.transform.up = transform.right;

    }

我想要这样,以便当用户转动齿轮时,它只会稍微旋转一下对象,因此用户可以在吊桥关闭之前将齿轮转动几次。

我尝试增加吊桥的欧拉角。我尝试将吊桥旋转设置为齿轮旋转,然后将该旋转除以2。

1 个答案:

答案 0 :(得分:0)

不要设置固定方向,而是使用正确的方法。

然后我将存储totalAngle,以便对其进行轮换,例如完成足够的轮播后,调用一些事件。

您仅将thingToRotate旋转到totalAngle / factor

// Adjust in the Inspector how often the cog thing has to be turned
// in order to make the thingToRotate perform a full 360° rotation
public float factor = 5f;

private float totalAngle = 0f;

[SerializeField] private Rigidbody2D thingToRotate;
private void OnMouseDrag()
{
    var mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    // this is shorter ;)
    Vector2 direction = (mousePosition - transform.position).normalized;

    // get the angle difference you will move
    var angle = Vector2.SignedAngle(transform.right, direction);

    // rotate yourselve correctly
    transform.Rotate(Vector3.forward * angle);

    // add the rotated amount to the totalangle
    totalAngle += angle;

    // for rigidBodies rather use MoveRotation instead of setting values through
    // the Transform component
    thingToRotate.MoveRotation(totalAngle / factor);
}

enter image description here