- Home /
Instantiating an object at click position
Hi. I am trying to spawn an object where I click down, but for some reason the object is being instantiated at a (seemingly) random location, every single time. There is a large cube that covers all of the viewable area, so I know the ray is hitting the collider...but what am I doing wrong? Also, is it possible to use ScreenPointToRay on a mobile platform, so I can port this script to iOS/Android (with some slight modifications, of course)? Thanks.
var Test : GameObject;
function Update () {
if (Input.GetButtonDown ("Fire1")) {
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray)) {
Instantiate (Test, transform.position, transform.rotation);
}
}
}
Answer by Andres-Fernandez · Aug 05, 2014 at 06:52 AM
You are setting the new object position and rotation to transform.position and transform.rotation, so it will be spawned where the object that creates the instance is located (instead of where the ray hits the collider).
You should use a RaycastHit to get the position where your ray hits the collider and use that position as the position for the new instance of the object. Check the examples here, look at the one with the raycasthit and the hit.point.
Answer by sethuraj · Aug 05, 2014 at 07:03 AM
The problem is you are instantiating the new object at the position of the gameobject to which this script is attached.It should be spawned at the ray hitting position.Something like this will do.
var Test : GameObject;
function Update ()
{
if (Input.GetButtonDown ("Fire1"))
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast(ray, hit, 100.0))
{
Instantiate(Test,hit.point,Quaternion.identity);
}
}
}
Attach this script to your camera or an empty gameobject and assign the prafab.For this script to work there should be a collider in the background.The ray should hit a collider and the new object will be spawned at the ray hitting point.If your collider is too far,increase the ray length from 100 to a higher value.
Hope this helps....
Your answer
Follow this Question
Related Questions
Following the cursor... 2 Answers
How to make a sprite/gameobject follow your finger on Android? 2 Answers
Move player with mouse help 0 Answers
Move to random position based off user's input of terrain size? 2 Answers
Move GUITexture with mouse 2 Answers