C# 如何使一个对象基于另一个对象旋转?
我有一个齿轮,用户可以旋转吊桥。目前,我有齿轮和吊桥以相同的速率旋转,如下所示: 这是我目前的代码:C# 如何使一个对象基于另一个对象旋转?,c#,unity3d,C#,Unity3d,我有一个齿轮,用户可以旋转吊桥。目前,我有齿轮和吊桥以相同的速率旋转,如下所示: 这是我目前的代码: [SerializeField] private Rigidbody2D thingToRotate; void OnMouseDrag() { Vector3 mousePosition = Input.mousePosition; mousePosition = Camera.main.ScreenToWorldPoint(mousePosit
[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;
}
我希望这样,当用户转动齿轮时,它只转动物体一点点,这样用户可以在吊桥关闭之前转动齿轮几次
我试着增加吊桥的欧拉角。我尝试将吊桥旋转设置为cog旋转,并将该旋转除以2。不要设置固定方向,而是使用正确的方法
- 确定当前
和变换.右
方向
- 如果使用
使用,而不是通过RigidBody2D
组件设置旋转Transform
总角度
,以便在足够旋转时调用某个事件
thingToRotate
只需旋转到总角度/系数
// 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);
}
可能的副本请不要发布副本。