am trying to instantiate a 3D object to fly in the direction where my mouse is pointing
am trying to instantiate a 3D object to fly in the direction where my mouse is pointing when i click on the screen, like am shooting but with an object, i've tried 2 different methods that i found online but none of then work, the object just instantiate on a fixed locations, i ran a test and Debug.log(mousePosition) on GetMouseButtonDown(0) and it always return a fixed position, bellow are the 2 different methods i've tried using, i dont know if it matters but there is also a canvas on the scene, i took screenshots of the scene and where the projectiles are spawning on the screen when i click, am new to unity and i can't seen to find an answer that works anywhere
{
private Vector3 mousePos;
public GameObject prefab;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousepos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Instantiate(prefab, new Vector3(mousepos.x, mousepos.y, -40), prefab.transform.rotation);
}
}
}
public GameObject prefab;
public float range = 1000f;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
shoot();
}
}
void shoot()
{
RaycastHit hit;
Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, range);
Instantiate(prefab,new Vector3(hit.point.x,hit.point.y,-40), Quaternion.LookRotation(hit.normal));
}
}
Your answer
Follow this Question
Related Questions
Raycast not drawing where i tell it 1 Answer
Need to press key 2 times to shoot 0 Answers
Having trouble with player health 0 Answers
2d Shooting to Mouse position 0 Answers
I'm having some trouble getting my shooting to work in unity2D 0 Answers