- Home /
Instantiate object at touch position problem
Hello everyone! i have a problem with an android game: i've written this code to instantiate a prefab at the touch position but the object (a projectile) is always instantiated at the center of the screen. What's wrong?
function Update () {
for (var i = 0; i < Input.touchCount; ++i) {
if (Input.GetTouch(i).phase == TouchPhase.Began) {
var touchPos = Input.GetTouch(i).position;
var createPos = myCam.ScreenToWorldPoint(touchPos);
Instantiate (projectile, Vector3(createPos.x, createPos.y, 4), Quaternion.identity);
}
}
}
Comment
Try using a post-increment operator in your for statement:
ins$$anonymous$$d of ++i, try using i++.
This will increment i after the loop runs ins$$anonymous$$d of before.
Best Answer
Answer by robertbu · Mar 12, 2013 at 02:11 AM
The most likely issue is that you are not setting the 'z' coordinate of touchPos before calling myCam.ScreenToWorldPoint(). 'Z' is how far in front of the camera to create the position. Try this (untested):
function Update () {
for (var i = 0; i < Input.touchCount; i++) {
if (Input.GetTouch(i).phase == TouchPhase.Began) {
var touchPos : Vector3 = Input.GetTouch(i).position;
touchPos.z = 4.0;
var createPos = myCam.ScreenToWorldPoint(touchPos);
Instantiate (projectile, createPos, Quaternion.identity);
}
}
}