I have a prefab turret. I want to on mouse click return position of were the turret needs to rotate to and rotate said turret to that rotation.
What I am doing is raycast from screen to world at mouse position and use hit.point as my target. I correctly get the target position I need. The problem arises when I need to rotate my object. Basically when I want to rotate my object on Y axis to that position the rotation is not correct. Here is the code I am using.
I think the problem has to do with the conversion from Quaternion to euler. Tbh I have also tried just feeding in the target rotation and the object still does not rotate correctly to the target position. In order to test if I am getting the correct point I have tried spawning a cube prefab at the target point and it spawns correctly so I am not 100% sure where the problem lies and that’s why I am finding it difficult to correct it. I appreciate any help you can give me. Thanks in advance
Your problem is that you use the components (.x) from the quaternion as euler input, the component of an Quaternion is in no way compatible to that and a user should only think about touching a quaternion component when he is a math crack and he knows what this means.
Instead of accessing the quaternion component, try to use the eulerAngles components of the quaternion:
Your next problem is, that you use your target position as direction, whih it isnt. You should calculate the direction from your turret to the target point and use this instead:
var direction = (hit.point - wholeBody.transform.position).normalized;
Also you can leave the euler thingy out when you create temp variable of your hit.point and set the y component to the value of the y component of your turrent position.
I am using Quaternion rotation so that I can get the function Quaternion.LookRotation(target) I prefer using Euler Angles.
Also, I understand the direction but should the value be fed than to Quaternion.LookRotation(direction)? want this value not be the same as the target value?
Atm I am working with the LookAt function. The problem is that my turret object is made up of 2 pieces the wholebody which needs to rotate on the y axis and the actual turret which needs to rotate in the x axis. The lookAt function does not give me the control I need to do that. I tried implementing the method you suggested although it limits the movement in the Y axis for the whole body it is not accurate as it is slightly off from the direction my mouse is pointing to.
Also, I tried using the Atan2 math function to add the limits for the turret object so it moves up and down by limit hit.Point.y and hit.Point.z and feeding the result to the angle axis unfortunately the turret was moving in the y and z axis so I am not sure what exactly I am doing wrong I am reading the documentation on it the get more familiar with the method.