This site requires JavaScript, please enable it in your browser!
Greenfoot back
kzb94
kzb94 wrote ...

2014/4/3

Getting gun to shoot when picked up

kzb94 kzb94

2014/4/3

#
I'm building a game where the character has to "pick up" a gun to shoot it. My code is: private void useGun() { int gun = 1; if ( canSee(Gun.class) ) { remove(Gun.class); gun = 0; } if (gun == 0 && Greenfoot.isKeyDown("space")) { getWorld().addObject( new Bullet(), getX(), getY()); Greenfoot.playSound("gunshot.wav"); } } Everything compiles, but the character can't use the gun once he picks it up. What am I doing wrong?
danpost danpost

2014/4/3

#
The code shown looks alright. If the actor cannot shoot then the problem is most probably in either the act method of this class or the gun class.
kzb94 kzb94

2014/4/3

#
This is my gun code public class Gun extends Actor { public Gun() { GreenfootImage image = getImage(); image.scale(image.getWidth() - 410, image.getHeight() - 410); setImage(image); } public void act() { } } And here's my act method for the person class. private int shootCount = 0; int health = 3; boolean isDown = false; public void act() { checkKeys(); stopAtWall(); useGun(); if (health > 0) { checkKeys(); stopAtWall(); useGun(); } else { setLocation(5, 565); health = 3; } }
danpost danpost

2014/4/3

#
Oh, the problem was in the initial code. You are declaring the 'gun' variable within the method and setting it to one every time it is executed. Move 'int gun = 1;' up above the 'private void useGun()' line.
kzb94 kzb94

2014/4/4

#
Okay, thanks! Also, I need to get the bullets to shoot from whatever direction the character is facing. How can I do that?
danpost danpost

2014/4/4

#
I would change this line:
1
getWorld().addObject( new Bullet(), getX(), getY());
to this:
1
2
3
Actor bullet = new Bullet();
bullet.setRotation(getRotation());
getWorld().addObject(bullet, getX(), getY());
You need to login to post a reply.