- Home /
Mouse aims at object ?
Hi all,
How to map mouse position on screen to world position ?
I know that this question has been asked a lot, but i have a problem.
In my game i display a crosshair instead of the mouse cursor for the player to aim. When "Fire" is clicked i want to instantiate a sphere(the missile i use) at a position relative to the cursor's position.
I tried Raycast, but it don work as i want it to be. This is almost close to what i want to achieve.
I use the following code:
// get the position of the mouse
var mousePos : Vector3 = Input.mousePosition;
var mouseToWorld : Vector3 = Camera.main.ScreenToWorldPoint (Vector3(mousePos.x , mousePos.y, Camera.main.nearClipPlane));
// instantiate a new object of the type of the missile
var instantiatedProjectTile : Rigidbody = Instantiate(projectTile, mouseToWorld, Quaternion.identity);
// adjust the velocity of the missle in the Z direction
instantiatedProjectTile.velocity = transform.TransformDirection(Vector3(0, 0, speed));
But it don work properly, the spheres don go in the direction of the object the cursor was aiming at.
P.S: I am using a Terrain as my playground.
Any help is appreciated,
Thanks,
Samer
Answer by Joshua · Aug 18, 2011 at 02:50 PM
When you instantiate them you want them not to give a rotation of Quaternion.identity but the rotation of the camera±
Instantiate( ..., ..., Camera.main.transform.rotation);
Then the velocity you want to give it is simply a local forward one
...velocity = instantiatedProjectile.transform.forward * magnitude
where magnitude is the magnitude of the velocity you want to give it.
how can i multiply the Rigidbody by the magnitude !!! "...velocity = instantiatedProjectile * magnitude "
Hah, I'm sorry, seems I forgot to write the final bit. It's the rigidbody's transform's forward vector you want. ;)
Your answer
Follow this Question
Related Questions
Rotate player to aim on one axis (Z-axis) towards mouse position/joystick - 2.5D (3D) 0 Answers
Cast a cursor into world space from a game object? 0 Answers
Make my Gunpoint aim/rotate on the z axis towards my mouse cursor 1 Answer
While holding down the mouse button make object rotate to mouse cursor 1 Answer
Top down aim at mouse 3 Answers