Unity3D: transform.LookAt() Y-Rotation is off

Viewed 44

I'm attempting to develop a third-person twin-stick shooter. The left stick moves the character and the right stick moves the reticle. I want to implement a laser sight, i.e. a thin cylinder extending from the player to the reticle.

I created a cylinder and ensured its pivot point is its bottom face. It is a child of the player GameObject and its local position is 0,0,0. I also ensured that the cylinder is extending towards the positive z-axis.

Every frame, I run the following code:

laserSightTransform.LookAt(reticleTransform, reticleTransform.up);
Debug.DrawRay(playerTransform.position, (reticleTransform.position - playerTransform.position), Color.green);

The second line is to draw a debug line to illustrate the correct rotation that laserSightTransform SHOULD have. However, as you can see in the below image, the laser sight is not being rotated properly: wrong rotation

Note that if the reticle and the player transforms are on the same height (have the same y-value) then the rotation is correct. However, as soon as the reticle is moved up or down, the discepancy in the above image shows up. If the reticle is above the player, the laser sight's y-rotation is below the reticle, and if the reticle is below the player, the laser sight's y-rotation is above the reticle.

I want the laser sight to always rotate to the exact center of the reticle, or the cube in the middle of it. I don't understand what's causing this discrepancy and would appreciate an explanation for what's going wrong here.

1 Answers

Well, this post was a waste of time as I've solved my own problem.

The issue here was that the player transform had a non-uniform scale of (0.5f, 0.4f, 0.5f), and the laser sight transform is a child of the player transform. I believe the non-uniform scale here was responsible for the discrepancy in the y-rotation, as it's not equal to the other two scale components. This explains why only the y-rotation is wrong.

I set the scale of the player transform to (1.0f, 1.0f, 1.0f) (and made the cylinder a child of this to maintain its size) in order to fix this.

Related