- Home /
Move to mouse position
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 is pretty simple. You can use the Vector3.Lerp function to achieve this. Use raycasting to get the mouse click position or the touch position. Then use the initial and the final position in the lerp function. The initial position being the position that the gameobject is at now and the final position being the click / touch position. You can find the article by The Game Contriver on the same here
$$anonymous$$ove to Touch / Click Position - The Game Contriver
Answer by robertbu · May 25, 2013 at 03:36 PM
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):
}
Your answer
Follow this Question
Related Questions
Call an exorcist. 1 Answer
Input System Can't Catch Event on Update 0 Answers
World mouse position not depending on Screen mouse position 2 Answers
Move player with mouse help 0 Answers
Move GUITexture with mouse 2 Answers