- Home /
Rotate object to make it point towards raycast hit point.
I'm modding the FPS Microgame Template project in Unity, which is a First Person Shooter game template available for free at the Unity Asset Store. The gun that comes with this template fires projectiles instead of using raycasts to simulate gunshots.
What I'm trying to do is make the gun look to the object that is directly in front of the player. That is, the gun muzzle should be rotated to face the hitting point of a ray coming from the camera.transform.forward.
I need the gun to point toward the center so the player can always have a precise feedback about where his shots will land. In the future, I will implement recoil simulation and all sorts of things that will influence the precision of the gun. But for that to work, I need it to have a baseline aiming point at, hopefully, the center of the screen.
I've tried all manner of things without much success. Currently, my closest solution is:
Vector3 origin = camera.transform.position;
Vector3 direction = camera.transform.forward;
RaycastHit hit;
if (Physics.Raycast(origin, direction, out hit, distance)){
WeaponParentSocket.transform.LookAt(hit.point);
}
This solution, unfortunately produces a very imprecise result, as you can see from the image below. The white line is the raycast from the camera and the pink line is the direction that the gun is currently pointing at:
How would one achieve the effect I'm looking for?