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

2013/2/27

Shoot a projectile (bullet) towards mouse location

kole9273 kole9273

2013/2/27

#
Okay so I'm having problems getting a bullet to shoot towards where my mouse was when I click Heres my code so far: Actor "Player" in act() has the checkKeys(); in checkKeys() it has: if(Greenfoot.mouseClicked(null)){ int x = mouse.getX(); int y = mouse.getY(); shoot(); in shoot(); it has: public void shoot() { Bullet bullet = new Bullet(); getWorld().addObject(bullet,getX(),getY()); bullet.turnTowards(x,y); } this should spawn the bullet at the player then turn the bullet towards where the mouse was clicked. in the Bullet class, all it has is move(3); (it constantly moves foward at a speed of 3). This isn't working for some reason. Help please
MatheMagician MatheMagician

2013/2/28

#
What isn't working exactly?
danpost danpost

2013/2/28

#
'x' and 'y' are declared as local fields in the 'checkKeys' method. You either need to make them instance object variables (not by declaring them as local to the method but by declaring them as class fields) or pass them directly to the 'shoot' method as parameter values.
TomazVDSN TomazVDSN

2013/3/2

#
danpost danpost

2013/3/2

#
Another field problem is that I do not see where 'mouse' gets assigned anything. To simplify things, getting mouse.getX() and mouse.getY() could be put directly in the 'shoot' method. This removes the issue of passing x and y to the shoot method. Your new code would be something like:
// in 'checkKeys' method
if (Greenfoot.mouseClicked(null)) shoot();

// the 'shoot' method
public void shoot()
{
    // the following two statements were added to the code
    MouseInfo mouse = Greenfoot.getMouseInfo();
    if (mouse == null) return;
    int x = mouse.getX();
    int y = mouse.getY();
    Bullet bullet = new Bullet();
    getWorld().addObject(bullet, getX(), getY());
    bullet.turnTowards(x, y);
}
You need to login to post a reply.