Hello everyone,
I’m hitting my forehead onto the table since several hours, but even the pain doesn’t solve my problem
I have a turret with this hierarchy:
DoubleLaserRifle
->LaserGun
-> Foot
-> Axis1
-> Axis2
-> Laser1
-> Laser2
Axis 1 only should turn left/right, Axis 2 only up down. So basically I’d have to split the lookat into 2 separate axis.
Based upon these two scripts which I found somewhere in the forum, I tried to implement the most obvious way:
//returns -1 when to the left, 1 to the right, and 0 for forward/backward
public static float AngleDir(Vector3 fwd, Vector3 targetDir, Vector3 up)
{
Vector3 perp = Vector3.Cross(fwd, targetDir);
float dir = Vector3.Dot(perp, up);
if (dir > 0.0)
{
return 1.0f;
}
else if (dir < 0.0)
{
return -1.0f;
}
else
{
return 0.0f;
}
}
public static float ContAngle(Vector3 fwd, Vector3 targetDir, Vector3 up)
{
float angle = Vector3.Angle(fwd, targetDir);
if (AngleDir(fwd, targetDir, up) == -1)
{
return 360 - angle;
}
else
{
return angle;
}
}
I tried to implement the “look at” like this:
// Create a plane with the position of the LRAxis and the up of the axis.
p = new Plane(LeftRightAxis.up, LeftRightAxis.position);
// Calculate the distance between the plane and the target position.
dist = p.GetDistanceToPoint(lookTarget.position);
// Project the lookTarget position onto the plane.
lookOnPlane = lookTarget.position - LeftRightAxis.up*dist;
// Calculate the direction between the axis position and the point on the plane.
dirToLookOnPlane = lookOnPlane - LeftRightAxis.position;
// Calculate the angle between the up vector and the dir to look on plane.
angle = ContAngle(LeftRightAxis.forward, dirToLookOnPlane, LeftRightAxis.up);
// Rotate locally about this angle.
LeftRightAxis.localRotation = Quaternion.Euler(0.0f, 0.0f, angle);
The target is to make this work with whatever orientation the turret has in space, not just null rotation.
If anyone has an insight on how to make this work, I’ll open for ideas