- Home /
Look at around one axis in local space
I want a weapon to aim at a specific GameObject while its parts rotate around specific axes : I need something like a transform.LookAt() in local space aroud specified axis. This :
public Transform yRotator, xRotator;
...
private void Update() // Look at target
{
Vector3 pos = target.position;
yRotator.LookAt(new Vector3(pos.x, 0, pos.z));
}
works for Y rotator... as long as spaceship the weapon is mounted on does not rotate. When it does, it all breaks, because Transform.LookAt() works in global space. This is also why X rotator is not included in this script - it does not work because it's a child of Y rotator (look at the image).
I have tried flatting target position converted to local space, but I can't make it work :
public Transform yRotator, xRotator;
...
private void Update() // Look at target
{
Vector3 pos = target.position;
Vector3 rotY = yRotator.InverseTransformDirection(target.position);
rotY.y = 0;
yRotator.LookAt(yRotator.TransformDirection(rotY));
}
UPDATE : Problem fixed :
public Transform yRotator, xRotator, target;
...
private void Update() // Look at target
{
Vector3 rotY = yRotator.InverseTransformPoint(target.position);
rotY.y = 0;
yRotator.LookAt(yRotator.TransformPoint(rotY), yRotator.parent.up);
Vector3 rotX = xRotator.InverseTransformPoint(target.position);
rotX.x = 0;
xRotator.LookAt(yRotator.TransformPoint(rotX), xRotator.parent.up);
}
Answer by sbsmith · Sep 17, 2019 at 02:18 AM
You could always build it backwards. The gun is the parent and the mounting geometry are the children. You can point your gun at the target, then rotate the mounts so it looks like they're attached properly to the ship. Since the mounts don't have any children, you don't need to worry about them messing up the position of your gun.
Your answer
Follow this Question
Related Questions
LookAt inaccurate rotation issue (javascript) 1 Answer
Lock rotation axis? 4 Answers
Why LookRotation works, but LookAt doesnt 0 Answers
Rotation using Unity2D 3 Answers
LookAt() with X axis 1 Answer