6 Replies Latest reply on Sep 10, 2007 6:48 PM by kglad

# Shooting a bullet.

Hello,

I am making this game. For the dude to shoot I use this code (it is applied to a movie clip that covers the Background:

--

onClipEvent (mouseDown) {
_root.e=1
endX = _root._xmouse;
endY = _root._ymouse;
startX = _root.b1._x
startY = _root.b1._y
}
onClipEvent (enterFrame) {
speed = 10;
if(_root.e==0){
_root.b1._x = _root.dude._x
_root.b1._y = _root.dude._y
}
if(_root.e==1){
_root.b1._x = _root.b1._x + (endX-startX)/speed
_root.b1._y = _root.b1._y + (endY-startY)/speed
}
}

--

'b1' is the bullet
'dude' is where it shoots from
startX/Y is where the bullet starts
endX/Y is where the person clicks, and the direction of the bullet, not unnecessarily where I want the bullet to go.

The problem is the closer I click to the dude when I shoot, the slower the bullet goes, how can I make this a fixed speed??

Thanks, sorry if this is rather confusing, or I left some important info out, If you have any questions just ask...

THANKS AGAIN!!

-Donald J
• ###### 1. Re: Shooting a bullet.
The math is a little tricky.

You need to convert the bullet vector into its angle using the Math.atan2 function.

Then you need to use the Math.cos and Math.sin functions to convert the vector into the x and y distances the bullet will travel (multiplied by your desired velocity).

This is the only way to make sure the bullet travels at a constant speed at any angle.
• ###### 2. Re: Shooting a bullet.
Thanks... I knew it shouldn't have been that straight forward....
• ###### 3. Re: Shooting a bullet.
OK... I've completly rewritten the script, after reading about sine and cosine... sadly we learn that next term in math :(... anywho, here's my new code:

--
xspeed = Math.cos(dude._rotation)
yspeed = Math.sin(dude._rotation)
if (Key.isDown(key.SPACE)) {
b1._x = b1._x + xspeed
b1._y = b1._y + yspeed
}
--
b1 - bullet
dude - the shooter

Now, it shoots in a nearly random direction... help?