c# - Shooting bullet towards target -
i'm using unity , trying bullet shoot @ target. clicking mouse , i'm wanting fire bullet in direction.
i have gotten coordinates of mouse click , tried compute vector. i've tried instantiate bullet prefab (which has rigidbody component , in front of scene) @ position , fire in direction of mouse.
i can see objects being instantiated in hierarchy pane can't see on screen!
not sure if i'm doing vector thing right (newb here), if click on yoshi's head, i'm getting (-2.0, -0.4)
. sound right?
code:
void firebullet(float mousepositionx, float mousepositiony) { vector2 position = new vector2(mousepositionx, mousepositiony); position = camera.main.screentoworldpoint(position); gameobject bullet = instantiate(bulletprefab, transform.position, quaternion.identity) gameobject; bullet.transform.lookat(position); debug.log(position); bullet.rigidbody2d.addforce(bullet.transform.forward * 1000); }
edit:
void firebullet(float mousepositionx, float mousepositiony) { vector2 position = new vector2(mousepositionx, mousepositiony); //screen space world space position = camera.main.screentoworldpoint(new vector3(position.x, position.y, -1)); vector2 direction = (input.mouseposition - transform.position).normalized; //instantiate bullet gameobject bullet = instantiate(bulletprefab, transform.position, quaternion.identity) gameobject; //rotates transform forward vector points @ targets current position bullet.transform.lookat(position); debug.log(position); //fire bullet bullet.rigidbody2d.addforce(direction * 1000); }
if camera facing z direction, bullet being spawned wrong z-coordinate. mentioned in comment, should change code tell unity z-position put bullet in (since each screen position, there infinitely many corresponding world positions, outside camera's view planes). third value need pass screentoworldpoint
, otherwise offset 0 , object spawned on top of camera:
float zpos = something; // wherever other scene objects are, more or less float camzpos = camera.main.transform.position.z; float zoffset = zpos - camzpos; vector3 bulletposition = camera.main.screentoworldpoint( new vector3(mousepositionx, mousepositiony, zoffset));
Comments
Post a Comment