坦克可以跑了,也可以控制方向,也可以控制静止,就剩下可以开跑啦。
子弹可以出世了。
作为子弹,是一个类别,所以要建一个类,子弹要有啥属性呢?
大小,
要有速度
要有方向,
要有颜色
跟坦克一样,要会绘画自己,得有绘画的方法,要移动,得有自己的移动。
子弹是圆形的
如此这个类是这样的:
package com.tavon.tank;
import java.awt.*;
public class Bullet {
private static final int SPEED = 40;
private static final int WIDTH = 5, HEIGHT = 5;
private int x, y;
private Dir dir;
public Bullet(int x, int y, Dir dir) {
this.x = x;
this.y = y;
this.dir = dir;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Dir getDir() {
return dir;
}
public void setDir(Dir dir) {
this.dir = dir;
}
public void paint(Graphics graphics) {
Color c = graphics.getColor();
graphics.setColor(Color.RED);
graphics.fillOval(x, y, WIDTH, HEIGHT);
graphics.setColor(c);
move();
}
private void move() {
switch (dir) {
case LEFT:
x -= SPEED;
break;
case UP:
y -= SPEED;
break;
case RIGHT:
x += SPEED;
break;
case DOWN:
y += SPEED;
break;
}
}
}
``在TankFrame中创建子弹:
Bullet b = new Bullet(210,210,Dir.DOWN);
并且绘制出来:
@Override
public void paint(Graphics graphics) {
myTank.paint(graphics);
b.paint(graphics);
}
这样子弹就可以飞了。