- Home /
Spawning an object in the direction of a mouse click?
Hello, I have a question about object spawning(this is for a 2D over head shooter, similar to geometry wars, super stardust HD, etc.). When the player clicks somewhere on the screen, I want to spawn a bullet, originating from the player, that is moving at a constant velocity towards wherever the player clicked (in a straight line), how would I do this?
Answer by Jesse Anders · Nov 07, 2010 at 07:46 AM
Transform the player position and/or the mouse click position so that they're in the same space (e.g. screen space, world space, etc.).
Subtract the player position from the click position and normalize to yield a direction vector for the object. (You'll most likely want to ignore any clicks where the click point is the same or nearly the same as the player position.)
If appropriate, orient the object accordingly, e.g. using Quaternion.LookRotation().
Make the object move over time using the method of your choice (e.g. make it a rigid body and give it an initial velocity, write a script that moves the object linearly at a fixed speed, etc.).
Your answer
![](https://koobas.hobune.stream/wayback/20220613082217im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Make a game object disappear when your camera looks at it. 1 Answer
Spawn objects (Instantiate) behind hierarchy 1 Answer
Having camera attack upon spawning player? 1 Answer
What is the reason for this NullReferenceException? 1 Answer