Hello!
I’m trying to figure out how to make a simple move-to-mouse script.
I have already searched but nothing works as I want it.
I need the player to move his mouse up & down, left & right and the gun to move accordingly. (image below)
I just need to make the gun more physical, not just standing in a place.
Any help?
This question has been answered on this list many time, but since the first dozen results of my Google search for an answer to direct you to either had wrong answers or answers that did not apply, I’ll put a new answer here. I’m assuming your gun is a physical object in world space. Mouse position is in screen coordinates. World space has depth and screen coordinates are 2D, so you need to decide how far in front of the camera you want to put your gun. You use Camera.ScreenToWorldPoint() to make the translation, and the ‘z’ parameter is the distance in front of the camera. So say you want to use 0.5 for the distance in front of the camera. Your tracking code (attached to the gun) could look like:
function Update() {
var v3Pos = Vector3(Input.mousePosition.x, Input.mousePosition.y, 0.5);
transform.position = Camera.main.ScreenToWorldPoint(v3Pos):
}