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

2013/11/19

Need help with spawning a bullet at a certain area on an object.

penorzilla penorzilla

2013/11/19

#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void shoot()
{
    MouseInfo mouse = Greenfoot.getMouseInfo();
     
    if(mouse != null)
    {
        if(shootdelay >= 20)
        {
            Bullet b = new Bullet();
            getWorld().addObject(b, getX(), getY()); //Adds bullet at the Players X and Y.
            b.turnTowards(mouse.getX(), mouse.getY()); //Turns the bullet towards the mouse.
            shootdelay = 0; //Resets the shootdelay back to 0.
        }
    }
}
This is my code for shooting. It spawns out of the middle of my character, but I want it to spawn out of the gun on the character. Issue is, the character constantly rotates in the direction of the mouse. I was wondering if anyone knew some sort of calculation or trick to make the bullet spawn at the gun on him. You can download my project here.
danpost danpost

2013/11/19

#
Just insert 'b.move(getImage().getWidth()/2);' after the 'turnTowards' statement.
penorzilla penorzilla

2013/11/19

#
danpost wrote...
Just insert 'b.move(getImage().getWidth()/2);' after the 'turnTowards' statement.
Thanks for your help, that only move the bullet to the edge of the player, but I figured out how to offset it over to the gun. I ended up with:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * Shoots a bullet from the Player in the direction of the mouse.
 */
public void shoot()
{
    MouseInfo mouse = Greenfoot.getMouseInfo();
     
    if(mouse != null)
    {
        if(shootdelay >= 20)
        {
            Bullet b = new Bullet();
            getWorld().addObject(b, getX(), getY()); //Adds bullet at the Players X and Y.
            b.turnTowards(mouse.getX(), mouse.getY()); //Turns the bullet towards the mouse.
            b.move(getImage().getWidth() / 2); //Moves the bullet to the edge of the player.
            b.setRotation(getRotation() - 90); //Turns the rotation of the bullet to offset it.
            b.move(21); //Moves the bullet over to the gun.
            b.turnTowards(mouse.getX(), mouse.getY()); //Turns the bullet towards the mouse, again.
            shootdelay = 0; //Resets the shootdelay back to 0.
        }
    }
}
You need to login to post a reply.