简体   繁体   English

Unity 中的偏心旋转对象

[英]Off-center rotate object in Unity

I have a laser turret in Unity3D, which I'd like to turn towards the enemies.我在 Unity3D 中有一个激光炮塔,我想把它转向敌人。 The turret consists of a "leg" and a "head" (selected on the picture 1 ).炮塔由“腿”和“头”组成(在图片1上选择)。 The head can pan and tilt around a spherical joint.头部可以围绕球形关节平移和倾斜。

I do the following:我执行以下操作:

    Vector3 targetDir = collision.gameObject.transform.position - turretHead.transform.position;
    float step = turnSpeed * Time.deltaTime;
    Vector3 newDir = Vector3.RotateTowards(turretHead.transform.forward, targetDir, step, 0.0f);
    turretHead.transform.rotation = Quaternion.LookRotation(newDir);

The problem is that since the pivot of the head is not aligned with the laser beam, the turret turns into the almost right direction, but it shoots above the target.问题在于,由于头部的枢轴未与激光束对齐,因此炮塔转向几乎正确的方向,但却射向了目标上方。 (It would hit perfectly, if the laser would come out of the red axis of the pivot.) (如果激光从枢轴的红色轴出来,它就会完美命中。)

Is there a builtin method or some trick to achieve the correct functionality other then doing the calculation myself?除了自己进行计算之外,是否有内置方法或一些技巧来实现正确的功能?

炮塔

Okay, here's the quick and easy way to do this.好的,这是执行此操作的快速简便的方法。 It's probably "better" to do it with proper trig, but this should give you the result you want pretty quick:使用适当的触发可能“更好”,但这应该很快就能给你想要的结果:

If you don't already have a transform aligned with the barrel, then create an empty GameObject and line it up (make sure it's a child of the turret so they move together).如果您还没有与枪管对齐的变换,则创建一个空的 GameObject 并将其对齐(确保它是炮塔的子级,以便它们一起移动)。 Add a reference to your script for it's transform.添加对脚本的引用以进行转换。

Then, in your first line, calculate from the new Barrel transform instead of the turretHead transform.然后,在您的第一行中,根据新的 Barrel 变换而不是 turretHead 变换进行计算。 Leave everything else the same.保持其他一切不变。 This way it calculates from the turret barrel, but moves the turret head.这样它从炮塔筒计算,但移动炮塔头。

Now, this approach isn't perfect.现在,这种方法并不完美。 If the pivot center is too offset from the barrel transform, then it would be less accurate over large moves, or when aiming at something close by, because the expected position when aiming would be different than the initial position due to the rotation pivot being elsewhere.如果枢轴中心与桶形变换偏移太大,则在大移动或瞄准附近物体时精度会降低,因为由于旋转枢轴在别处,瞄准时的预期位置将与初始位置不同. But this can be solved with iteration, as the calculation would become more accurate the closer it is to it's desired goal.但这可以通过迭代解决,因为计算越接近预期目标就会变得越准确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM