- Home /
Spawn on Mouse Locatiion
I'm trying to make a script for spawning an item within a radius around where the mouse is positioned on screen, like in the example below. I've made a script that works for overhead viewpoint, but on third person view, behind the shoulders, it is off by a wide margin when it comes to depth perception. So can anyone:
Show me how to correct it
Draw the radius or point on screen so the player will know where it will be spawned
My Code so far: Code:
if(Input.GetMouseButtonDown(0)){
var playerPlane = new Plane(Vector3.up, transform.position);
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hitdist = 0.0;
if (playerPlane.Raycast (ray, hitdist)) {
var targetPoint = ray.GetPoint(hitdist);
}
Spawn();
}
}
Example: http://youtu.be/M0EdKtq9fUo?t=1m12s
Thread Link: http://forum.unity3d.com/threads/109172-Spawn-on-mouse-location?p=723067#post723067
I think it has something to do with the Player Plane, but my efforts to alter it end badly.
Answer by Umbra · Oct 25, 2011 at 07:56 PM
Camera:ScreenToWorldPoint could be what you're looking for. Remember that the engine really has no way of telling the "depth" of the game, especially not in third person, other than distance from the camera.
I don't know exactly what it is you're trying to do, but maybe let the user scroll up and down to adjust the distance?
It requires the mouse input to deter$$anonymous$$e where to spawn it. If I could cast the ray through the screen and against the collider, then I could get somewhere.
Isn't the mouse input (i.e. the mouse position) exactly what you're trying to do, though?
I use something similar in a script of $$anonymous$$e. It's for turning the main character, but I think you may find some use in it.
var ray = Camera.main.ScreenPointToRay(Input.mousePosition); var hit:RaycastHit; if (Physics.Raycast(ray, hit, 100)) { var tarPos:Vector3 = Vector3(hit.point.x, 0.5, hit.point.z); transform.LookAt(tarPos); }
You basically shoot a ray from the camera through the world point that the mouse is in, and co$$anonymous$$g up with a point in the world. That point could then be the center of the effect you want to spawn.
Answer by ptdnet · Oct 23, 2011 at 09:34 PM
Take a look at Random.onUnitSphere. It gives you a position on a sphere, which you could center on your mouse.
It's a function that comes with Unity. Specifically: http://unity3d.com/support/documentation/ScriptReference/Random-onUnitSphere.html
No, what I mean is that it shows a random spot on a sphere but nothing that I'm doing uses random or a sphere in this particular script.
Your answer
Follow this Question
Related Questions
Spawn prefab where i click. 1 Answer
spawn prefab on mouse up 1 Answer
Multiplayer click and spawn 1 Answer
Spawn Objects Where i click 2 Answers
Make a object spawn 1 Answer