飞船跟随鼠标移动,按 a键 发射子弹
主类:
float x, y;
//x,y是圆心坐标
float easing = 0.01;
Particle p;
float diameterWidth = 32.0,
diameterHeight = 4.0;
void draw_a_UFO(float x, float y)
{
fill(255, 0, 0);
ellipse(x, y, diameterWidth / 3, diameterHeight * 2.5);
fill(0, 255, 0);
ellipse(x, y, diameterWidth, diameterHeight);
int colornum = int(random(0, 255));
fill(colornum);
ellipse(x-diameterWidth/2, y, diameterWidth / 3, diameterHeight * 2.5);
ellipse(x+diameterWidth/2, y, diameterWidth / 3, diameterHeight * 2.5);
}
boolean isShoot = false;
boolean isKeyPressedFirst = true;
boolean isFirst = true;
void setup()
{
size(720, 404);
smooth();
x = 0.5 * width;
y = 0.5 * height;
}
void keyPressed() {
if (key == 'a') {
isKeyPressedFirst= true;
}
}
void keyReleased() {
if (key == 'a') {
if (isKeyPressedFirst) {
println("aaa");
isShoot = true;
isFirst = true;
isKeyPressedFirst= false;
}
}
}
void draw()
{
background(0);
float targetX = mouseX,
targetY = mouseY;
x += (targetX - x) * easing;
y += (targetY - y) * easing;
noStroke();
draw_a_UFO(x, y);
if (isShoot) {
if (isFirst) {
p = new Particle(new PVector(x, y));
isFirst = false;
}
p.run();
}
}
子弹(粒子)类:
class Particle {
PVector location;
PVector velocity;
PVector acceleration;
float lifespan;
Particle(PVector l) {
// The acceleration
acceleration = new PVector(0, 0);
// circel's x and y ==> range
velocity = new PVector(0, random(-20, 0));
// apawn's position
location = l.copy();
// the circle life time
lifespan = 255.0;
}
void run() {
update();
display();
}
void update() {
velocity.add(acceleration);
location.add(velocity);
lifespan-=1.0;
}
boolean isDead() {
if (lifespan <= 0) {
return true;
} else {
return false;
}
}
void display() {
// border
stroke(0, lifespan);
// border's weight
strokeWeight(1);
float r = random(0,255);
float g = random(0,255);
float b = random(0,255);
// random the circle's color
fill(r,g,b, lifespan);
// draw circle
ellipse(location.x, location.y, 8, 8);
}
}
效果图如下: