I am a beginner at Greenfoot and I'm working on a top-down shooter. I want to offset the bullets the player is shooting slightly so they appear at the barrel of the gun, not at the center of the player.
The problem is my game allows the player to rotate the player sprite using the mouse(the actor points in the direction of the mouse), so I can't simply add a certain amount to x and y.
Here is my code for the player class:
public class Player extends Actor
{
/**
* Act - do whatever the Player wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
int shootTimer; //the delay between shots
public void act()
{
MouseInfo m = Greenfoot.getMouseInfo();
shoot(); //bullet points the same direction as player, and moves in that direction
shootTimer++;
if(m != null)
{
turnTowards(m.getX(), m.getY()); //Player points toward mouse coordinates
}
if (Greenfoot.isKeyDown("w"))
{
move(3);
}
if (Greenfoot.isKeyDown("s"))
{
move(-3);
}
}
public void turnTowards (int x, int y)
{
double dx = x - getX();
double dy = y - getY();
double angle =
Math.atan2(dy,dx)*180.0/Math.PI;
setRotation( (int)angle );
}
public void shoot()
{
MouseInfo m = Greenfoot.getMouseInfo();
if (m != null)
{
if (m.getButton() == 1 && shootTimer > 10)
{
Bullet bullet = new Bullet();
getWorld().addObject(bullet, 0, 0);
bullet.setLocation(getX(), getY());
bullet.setRotation(getRotation());
shootTimer = 0;
}
}
}
