I am making a character swing a sword in the direction of the point the mouse clicks by generating two vectors: one from the character’s position to the click point, and the second from the character’s position to the tip of the sword. The, the code should find the angle between the two vectors, convert it into a quaternion, and finally rotate the sword. As of now, the sword only moves slightly and I get and error saying that swordPoint is null even though I have it assigned in the inspector.
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(ray, out hit);
Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);
ClickPoint = hit.point;
swing = transform.InverseTransformDirection(ClickPoint).normalized;
sword = transform.InverseTransformDirection(sP.transform.position).normalized;
axis = Vector3.Cross(sword, swing);
angle = Mathf.Acos(Vector3.Dot(sword, swing));
rotation = Quaternion.AngleAxis(angle, axis);
swordHilt.transform.rotation = rotation;
Well, first of all you can simply use Quaternion.FromToRotation which does calculate a relative rotation that would rotate the first vector so it matches the second. Though there are a few things in your code that should be addressed.
First of all Physics.Raycast returns a boolean value indicating if the ray hit something. If this method returns false you must not process or read any values of the hit structure as the data is invalid since nothing was hit. So make sure you handle this case properly.
Next is I would not recommend to calculate the relative angle and axis locally. Especially since you apply the quaternion as a worldspace rotation in the end. This will most likely cause all sorts of issues. Stay in worldspace.
Finally you just assign the relative rotation you just calculated as absolute rotation to your “swordHilt” object. Unless that object is not rotated at all initially this will not result in the rotation you’re looking for. You usually want to multiply the relative rotation by the current rotation in order to apply the relative rotation to it. Keep in mind that this will instantly rotate your object to the target orientation. So there is no visible motion over time.
About your null reference error, well there’s not much to say about that. If you get a null reference exception it means the variable is not set to a valid object. Either you somehow loose the reference or it was never set to begin with. Note that in your code you used an object called
sP but in your description you talk about “swordPoint”. Did you rename the variable or do you have two? Maybe you’re using the wrong one? Those are all trivial things to sort out.