- Home /
Firing towards mouse- aim in all directions?
I am using this code to fire a bullet ('launch' prefab) from the player towards the mouse position
(in Update)
}if(Input.GetKeyDown("b")){
var distFromCam = Camera.main.transform.InverseTransformDirection(transform.position).z ;
var targetScreenPos = Input.mousePosition;
targetScreenPos.z = distFromCam;
var targetPosition = Camera.main.ScreenToWorldPoint(targetScreenPos);
var go: GameObject = Instantiate(launch, fire.position, transform.rotation);
go.transform.LookAt(targetPosition);
I think this is only paying attention to the camera's actual position instead of its position and rotation- When the camera rotates around 180, it will still only fire on the world axis' z from the camera. How do I tell this to pay attention to the camera's z rotation? Thanks
Is this a top-down shooter? An FPS? A TPS? A sidescroller? $$anonymous$$ore info please.
Answer by aldonaletto · Nov 20, 2011 at 07:57 PM
This approach will not work, because you can't figure out the distance from the camera to the point you want to shoot. You should use ScreenPointToRay and Physics.Raycast (see example here) to find the world point "under" the mouse pointer:
if(Input.GetKeyDown("b")){ var ray = Camera.main.ScreenPointToRay(Input.mousePosition); var hit: RaycastHit; if (Physics.Raycast(ray, hit)){ // executes only if some object hit (sky doesn't count) var targetPosition = hit.point; var go: GameObject = Instantiate(launch, fire.position, transform.rotation); go.transform.LookAt(targetPosition); ... }
Thank you so much for helping me- I see now what was going on, and this does make more sense.
Whoa, whoa, hold up a sec- There is no exact point I need to shoot at. I think I am not explaining right. The code I am using works, its just that it only works with the world's forward direction (z) ins$$anonymous$$d of the camera's forward rotation. I just need a way to switch that.
BOO$$anonymous$$! FIGURED IT OUT! If you add 360 to end of distFromCam in the original code, you can fire in all directions!