0

I am programming a game in Unity. I am trying to spawn a sphere in space everytime the user clicks the interface. I can spawn the spheres, but the spheres are always at coordinates of around (200,200, 0) and (400,400,0), but the spheres should be spawned at where the pointer is on the screen. It's my code below, can someone help? I am writing in C#:

using UnityEngine;
using System.Collections;

public class myscript : MonoBehaviour {

//initialize a circle
public GameObject Node;
public float cooldown = 1;

bool clicker;
float clicktime = 0;

GameObject node; //reference to the prefab

// Use this for initialization
void Start () {
}

//In everyframe you can 
void Update () {
    clicker = Input.GetMouseButtonDown(0); //obtaining the input
    clicktime += Time.deltaTime;

    }

//Check whether you can shoot
void FixedUpdate(){
    if (clicker == true && clicktime >= cooldown) { //if the clicker is clicked and the previos clicking is done
        SpawnCircle(); //spawn a circle
        clicktime = 0; //reset timer
    }
}

void SpawnCircle(){
    //this creates a new game object
    x = Input.mousePosition.x
    y = Input.mousePosition.
    node = GameObject.Instantiate (Node,Input.mousePosition,Quaternion.identity) as GameObject;
    //settings that we initalize our object with
    //node.transform.position = new Vector3(Input.mousePosition.x, Input.mousePosition.y,0);
}

}
Brenda So
  • 191
  • 1
  • 8

1 Answers1

1

You need to calculate ScreenToWorld Coordinates. With Unity it's easy actually.

https://unity3d.com/learn/tutorials/modules/beginner/physics/raycasting

TarikGuren
  • 83
  • 1
  • 6