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

2019/2/14

Rotation of my bullet

Sam123123 Sam123123

2019/2/14

#
I added bullet code to my character but I don't know how to make my character shoot in the direction of which my character is facing. I have tried about anything on the internet but nothing seems to work. this is my code.
public class Soldaat extends Actor
{
    public void act()
{
   {
       if (Greenfoot.isKeyDown("up")) {
           setLocation(getX(),getY()-3);
           this.setImage("characters1Up.png");
        }
       if (Greenfoot.isKeyDown("down")) {
           setLocation(getX(), getY()+3);
           this.setImage("characters1Down.png");
        }
       if (Greenfoot.isKeyDown("left")) {
           setLocation(getX()-3, getY());
           this.setImage("characters1Left.png");
        }
       if (Greenfoot.isKeyDown("right")) {
           setLocation(getX()+3, getY());
           this.setImage("characters1Right.png");
        }
       {
           checkFire();
        }
    }
}
public void checkFire()
{
   if(Greenfoot.isKeyDown("space")) 
   {
       getWorld().addObject(new Bullet(), getX(), getY());
       Bullet.setRotation(getRotation());
    }
  }
}
danpost danpost

2019/2/14

#
Sam123123 wrote...
I added bullet code to my character but I don't know how to make my character shoot in the direction of which my character is facing. I have tried about anything on the internet but nothing seems to work. << Code Omitted >>
The rotation of your Soldaat actor never changes;, so getRotation() will always return zero at line 32. Bullet on line 32 is a Class name and classes do not have a rotation. If you were to set the rotation of a new bullet object to that of the actor, you would need a reference to the bullet created, like this:
Bullet bullet = new Bullet; // "bullet" refers to new object
bullet.setRotation(getRotation());
getWorld().addObject(bullet, getX(), getY());
Bullets will stream out when the firing key is down (about 60 bullets will be created per second). You need either a delay counter or a key state indicator to regulate the flow/creation of bullets. As is, there is no way to determine which direction the Soldaat actor last moved; so the rotation at which to set a new bullet to cannot be determined. You will need something to indicate which way was moved last.
You need to login to post a reply.