- Home /
How to make a gameobject be exactly where the mouse is.
So I have an ability in a game that I am making that spawns in a bomb and it follows the mouse for 5 seconds then explodes. I have all of the other scripts ready, but none of it will work unless I have the bomb follow the mouse. I think it would be easier if I made the bomb follow a gameobject that is just on the mouse. So if you can help out with that, or inform me that their is in fact an easier way to have something follow the mouse.
Answer by tressix · Mar 07, 2014 at 04:11 AM
Simplest way is to do this:
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition)
But you're not going to get a depth position that's useful because your mouse has no inherent 3D location, it has a 2D location in the viewport, so the depth will probably be returned as the depth of the camera.
To get usable depth I've used two different methods.
1 - Set the depth manually.
var x = Input.mousePosition.x;
var y = Input.mousePosition.y;
transform.position = Camera.main.ScreenToWorldPoint(Vector3 (x, y, yourZdepth));
The downside here is that the object won't always look like it's where the mouse is on the screen.
2 - Use ScreenPointToRay with a virtual plane.
var plane : Plane = new Plane(Vector3(0, 1, 0), Vector3(1, 1, 0), Vector3(1, 0, 0));
Then in Update():
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var rayDistance : float;
if(plane.Raycast(ray, rayDistance)) {
targetPosition = ray.GetPoint(rayDistance);
}
transform.position = targetPosition;
Make the movement smoother by doing something like:
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, velocity, 0.05);
EDIT - You could also use ScreenPointToRay but then do a raycast against the scene geometry instead of that virtual plane to get a point on your game world surfaces.
All code is untested but should get the general point across.
Your answer
Follow this Question
Related Questions
Tank Turret Movement By Mouse 2 Answers
Mouse movement relative to screen space 0 Answers
Directional mouse movement independent from position? 1 Answer
Translating multiple GameObject using the mouse (2D) 0 Answers
Mouse movement on grid 1 Answer