How to make a bullet fire from the cannon angle

edited July 2017 in Questions about Code

Hi! I have made a code for rotating the tank by pressing 'l' and 'r' and a bullet class using vectors and I have no idea how to make the bullet fire from the same angle as the cannon. Here is the code I wrote:

PImage cannon;
PImage bullet;
int x = 250;
int y = 100;
float rota=0;
void setup() {
  size(700, 700);
  background(0);
  cannon = loadImage("cannona.png");
  bullet = loadImage("fireball.png");
  image(cannon, width/2, height/2, 100, 200);
}

void draw() {

}

void keyPressed() {

  switch(key) {
  case 'l':
    background(0);
    pushMatrix();
    imageMode(CENTER);
    translate(x+cannon.width/2, y+cannon.height/2);
    rotate(rota);
    image(cannon, 0, 0, 100, 200);
    translate(x+cannon.width/2, y+cannon.height/2);
    popMatrix();
    rota=rota+0.1;
    break;
  case 'r':
    background(0);
    pushMatrix();
    imageMode(CENTER);
    translate(x+cannon.width/2, y+cannon.height/2);
    rotate(rota);
    image(cannon, 0, 0, 100, 200);
    translate(x+cannon.width/2, y+cannon.height/2);
    popMatrix();
    rota=rota-0.1;
    break;
  }
}

class Bullet {

  PVector pos;
  PVector vel;
  PVector acc;
  float friction = 0.99;
  float speed;

  float direction; 



  Bullet(PVector _pos, float _direction, float _speed) {
    pos = _pos.copy();
    vel = new PVector();
    acc = new PVector();
    direction = _direction;
    speed = _speed;
    this.initVel();
  }

  void update() {

    vel.add(acc);
    vel.mult(friction);
    pos.add(vel);
    acc.mult(0);
  }

  void display() {
    stroke(0, 255, 0);
    strokeWeight(2);
    pushMatrix();
    translate(pos.x, pos.y);
    line(vel.x*0.5, vel.y*0.5, 0, 0);
    popMatrix();
  }


  void initVel() {
    PVector dir = new PVector(cos(direction), sin(direction));
    dir.mult(speed);
    this.applyForce(dir);
  }

  void applyForce(PVector _force) {
    acc.add(_force);
  }

  boolean isDone() {
    return (pos.x < 0 || pos.x > width || pos.y < 0 || pos.y > height);
  }
}
Tagged:

Answers

  • is this homework? how do you have a Bullet class but not know how to use it?

    add more code to your keyPressed() method so that 'f' key (for instance) creates a new bullet.

    make this bullet a global variable, call it, say, myBullet.

    you'll need to move all the drawing that you do in setup() into draw() and add a call that draws the bullet (myBullet.display())

    you'll need to call myBullet.update() to move it, every frame, and call myBullet.isDone() to see if it's still moving.

Sign In or Register to comment.