c# - 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.
解决方案
不要设置固定的方向,而是使用正确的方法。
Mathf.SignedAngle
确定电流transform.right
和 电流之间的角度差direction
如果使用
RigidBody2D
使用Rigidbody2D.MoveRotatio
n而不是通过Transform
组件设置旋转。
然后我会存储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);
}
推荐阅读
- java - 协调两个线程时的并发问题
- ios - 如何在设备上运行 tns run ios?
- amazon-web-services - 使用 CloudFormation 模板对 ASG 使用 UpdatePolicy 时,何时使用 AutoScalingScheduledAction?
- python - 如何在新的 venv 中升级到 Tensorflow2?
- cortex-m - 如何计算指令之间的字节数
- python - Python boto3 异常处理
- rust - 将 Actix 身份与瞻博网络 GraphQL 结合使用
- c - 这个按位表达式有什么作用,给定最终值可以反转吗?
- r - 将循环制作的图保存在文件中
- html - 如何制作循环背景元素?