Instantiate where i touch

I´m trying to instantiate a prefab when i touch a Object, but i need what the instantiate object take the X of my Touch position in my 3d world.

This is my code:

var newObject : GameObject;
function Update () {
	for (var Touch : Touch in Input.touches) {
		if (Touch.phase == TouchPhase.Began) {
			
			var ray = Camera.main.ScreenPointToRay (Touch.position);
			if (Physics.Raycast (ray)) {
				
				Instantiate (newObject,Vector3(ray),transform.rotation);
				
			}
		}
	}
}

2 Answers

2

The point hit by the ray can be returned if you supply a RaycastHit variable as the second Raycast parameter - instantiate the object at this point, like below:

 
var ray = Camera.main.ScreenPointToRay (Touch.position);
var hit: RaycastHit;
if (Physics.Raycast (ray, hit)) {
    Instantiate (newObject,hit.point,transform.rotation);
}

Thank you, it’s very useful for me.
It’s works !!!

For any immediate input tests (<i>GetKeyDown()</i> and <i>GetKeyUp()</i>), this is a bad idea, since those can be missed entirely by asynchronous timings of <i>Update()</i> and <i>FixedUpdate()</i>. That said, it's still "wrong" to use <i>FixedUpdate()</i> for <i>Input.GetKey()</i> (and similar) as well, so you should move your logic for input into <i>Update()</i> in general.

Also note that Fixed Update goes with a framrate of 50 frames per second; that is pretty slow alone but the operation system has some delay too. But that is not noticeable (I've done some simple experiments with Input delay 50 ms delay is totally fine)