Shooting left and right


(Nate ) #1

Hello all! This is a common issue that I have had before and I can’t seem to figure it out. Basically I have a player who shoots on the X axis, and depending on his direction he shoots either left or right. I have that working fine. The issue is, say he is shooting left meaning he is facing left. If he changes to face the right any bullets he has fired left that has not been destroyed yet automatically change direction to the right. I know the solution has to be very simple but I can’t think of it, and the funny part is I have had this issue before and fixed it.

Here is the update on my bullet class:

override public function update():void
		{
			if (thePlayer.direction == 2)
			{
				x += 8;
			}
			if (thePlayer.direction == 1)
			{
				x -= 8;
			}
			
			if (collide("level", x , y))
			{
				this.destroy();
			}
		}

And this is my player class where the bullets are fired:

if (Input.pressed(Key.CONTROL))
			{
				FP.world.add(new theBullet(this.x + 5, this.y + 20));
			}

I think I have to do something else in the bullet class but I don’t remember what.

Thanks guys


(David Williams) #2

Let’s think about what’s happening.

  • The player is facing direction 1.
  • The player adds a new bullet, which is traveling in direction 1.
  • The player changes direction to direction 2.
  • [Problem] The bullet sees in its update that the player is in direction 2, and so begins moving in that direction.

(Nate ) #3

So I need to change how I am adding the bullet?


(David Williams) #4

That, or how cough or perhaps when cough the bullet decides which direction to go in.


(Nate ) #5

So instead of the bullet direction sponging off of the player direction I make another variable for the direction of the fired bullet?


(Jacob Albano) #6

Yes; after your bullets are created they shouldn’t be aware of the player at all.

// player
private function shoot():void
{
    var direction:Int = 0;
    if (facingLeft) direction = -1;
    if (facingRight) direction = 1;

    world.add(new Bullet(x, y, direction));
}
// bullet
override public function update():void
{
    super.update();
    x += direction * speed;
}

(Nate ) #7

This is kind of what I ended up doing from what Deamonr said, but I switched over to yours! Thanks Jacob!


(Jacob Albano) #8

It’s funny you should say that, because literally all I did was demonstrate his approach. :stuck_out_tongue:


(David Williams) #9

That’s the beauty in the trade: there’s no ‘correct’ way to do it.

AKA: There’s more than one way to skin a cat.


(Zachary Lewis) #10

But, there are also tons of wrong ways to skin a cat. Like, with bullets.