x


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.

more ▼

asked Jan 31 '10 at 10:12 PM

Manny gravatar image

Manny
1 1 1 1

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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);
    }
}
more ▼

answered Jan 31 '10 at 11:08 PM

Jaap Kreijkamp gravatar image

Jaap Kreijkamp
6.4k 20 26 70

(comments are locked)
10|3000 characters needed characters left

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.

more ▼

answered Jan 31 '10 at 11:20 PM

xToxicInferno gravatar image

xToxicInferno
485 24 28 41

add a minus sign before the word power :-)

Jan 31 '10 at 11:38 PM Jaap Kreijkamp

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!

Feb 01 '10 at 12:05 AM xToxicInferno
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5091
x1040

asked: Jan 31 '10 at 10:12 PM

Seen: 1433 times

Last Updated: Feb 01 '10 at 12:21 PM