I know that there are some posts out there that kind-of cover this, but I'm new to Unity and I'm working on a FPS prototype trying to figure out how to have the gun always point to the cursor in the center of the screen.
There are a few good scripts out there, however I do not know where to place them, or if they are necessarily the best thing as far as performance is concerned (using Ray casting and getting the distance of the nearest object at the position of the cross-hairs)
There are two scripts I have found in the forums below. Which is better to use for performance, and where do I actually place the script?, on What GameObject?
And This one:
Would the best solution be to translate a point in the screen to a world point, and then parent the gun's aim and cross-hair element to the mouse's position? Any help would be amazing, thank you so much!
asked Mar 12 '10 at 09:40 PM
One important question is what kind of FPS you are making, since you seem to be kind of describing a duck-hunt type game in which the camera has a fixed position (which would be true if you were to have the crosshair and aim dependent on the mouse position), even though both of the scripts you have fire the gun directly to the middle of the screen.
If you want to do a traditional FPS in which the camera moves with the mouse I would suggest making the crosshair and aiming dependent on the main camera (always being at the middle of the screen), and then having your gun object be a child of the main camera (so that it will move with it). Using the ScreenPointToRay would work for that, you would just need to get a hold of the camera (for instance through a findbytag):
Also I wouldn't worry about the performance effects of the raycasts in this case.
answered Mar 12 '10 at 10:03 PM
I have no idea why that worked, but it worked like a charm. Earlier, I had tried to put the script on an empty child of the camera and then use that child as the parent of the weapon. That caused the center of the weapon to rotate around the center of the screen. Jason's way caused the weapon to remain fixed on the center of the screen, moving the weapon in a fixed point along with it.
Thanks, Jason. You've saved me a few headaches.