- Home /
How to shoot in different directions with different keys?
Well i made a Mario-esque game, where i can run, jump and shoot. Well the problem here is the shooting part. When i shoot, i either shoot forward, or out into 3D space. For the shooting script i got:
var Char_Bullet : Transform; var power = 2000.0;
function Update () { if(Input.GetKey("k")) { var bullet = Instantiate(Char_Bullet, GameObject.Find("Gun_Spawn").transform.position, Quaternion.identity); bullet.rigidbody.AddForce(transform.forward * power); } }
What i want to do is, have 'J' and 'L' be the direction i fire in, while 'K' is the fire button. This script only shoots with 'K' and that is, like i said, into 3D space. Any help would be appreciated.
Answer by Jaap Kreijkamp · Jan 31, 2010 at 11:08 PM
It depends a bit on how your world is oriented along the axis, but basically change the transform.forward
to transform.right
(and for other way negate power) and you probably are shooting in the right direction.
Okay, without doing anything smart the code would end up something like:
var Char_Bullet : Transform; var power = 2000.0;
function Update () { if(Input.GetKey("j")) { var bullet = Instantiate(Char_Bullet, GameObject.Find("Gun_Spawn").transform.position, Quaternion.identity); bullet.rigidbody.AddForce(transform.right -power); } else if(Input.GetKey("l")) { var bullet = Instantiate(Char_Bullet, GameObject.Find("Gun_Spawn").transform.position, Quaternion.identity); bullet.rigidbody.AddForce(transform.right power); } }
Answer by xToxicInferno · Jan 31, 2010 at 11:20 PM
That helps to shoot to the right. This still leaves shooting to the left not working. Could you please explain how to negate the power? Because simply making it less or even a negative, it just randomly sprays the bullets.
add a $$anonymous$$us sign before the word power :-)
The negative sign made it so they sprayed the right way, but the problem was my character was in between the spawn point, and where they wanted to go...so i simply made a 'Gun_Spawn1' on the opposite side. Thanks!