首页 > 解决方案 > How do I make an object rotate based on another object?

问题描述

I have a cog that the user can turn to rotate a drawbridge. Currently I have the cog and the drawbridge rotating at the same rate, like so: https://gyazo.com/14426947599095c30ace94a046e9ca21

Here is my current code:

[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;

    }

I want it so that when the user turns the cog it only turns the object a little bit, so the user can turn the cog a few times before the drawbridges closes.

I've tried adding to the drawbridges euler angle. I've tried setting the drawbridges rotation to the cog rotation and dividing that rotation by 2.

标签: c#unity3d

解决方案


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

然后我会存储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);
}

在此处输入图像描述


推荐阅读