我的代码可以生成与在海洋中航行的船的不同方向相对应的射弹。方向由物体的速度决定,顺时针循环,其中0为北至7为西北。在我的keyPressed功能中,我可以用箭头键移动就好了。此外,如果我按空格按钮激活大炮,一切都很顺利,除非我向西北方向前进。在这种情况下,没有发射子弹,我的java程序发出一点哔声。
keyPressed代码
public void keyPressed(KeyEvent e) { //TODO switch to keyBindings to remove pause after the initial key press
// if the key is pressed, move up
if(e.getKeyCode() == KeyEvent.VK_DOWN){
//move the board down.
dy = speed;
}
if(e.getKeyCode() == KeyEvent.VK_UP){
// move spaceship upwards
dy = -speed;
}
if(e.getKeyCode() == KeyEvent.VK_LEFT){
dx = -speed;
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
dx = speed;
}
dir = myShip.getDirection(dx, dy); // determine direction so that the draw function can draw the correct sprite.
if(e.getKeyCode() == KeyEvent.VK_I){ // info key.
System.out.println(getCurrentTile().getClass().getName());
Tile t = getCurrentTile();
if(t.isDockTile()){
Docks d = (Docks) t;
System.out.println(d.getName());
}
}
if(e.getKeyCode() == KeyEvent.VK_M && getCurrentTile().isDockTile()){
if(getCurrentTile().isDockTile()){
mission = new Mission(); // create a new mission.
Docks d = (Docks) getCurrentTile();
mission.init(d); // initialize using the dock's name.
isMissionAssigned = true; // yay! we have a Mission!
} else {
System.out.println("You can't get a mission if you're not at a port!");
}
}
// fire a bullet
if(e.getKeyCode() == KeyEvent.VK_SPACE){ // TODO - NW seems to be broken.
bullet = new Projectile(bulletSpeed, dir, 10);
System.out.println("Created a bullet with direction " + dir);
bullet2 = new Projectile(bulletSpeed, myShip.getOppDir(dir), 10);
}
}
我的两个功能是获得船的方向。
public int getOppDir(int d){
// since there are 4 directions, add 4 to get opposite.
// use opposite to move back to 0 if > than 8
for(int i = 0; i < 4; i++){
d++;
if(d >= 8){
d = 0;
}
}
return d;
}
public int getDirection(int dx, int dy){ // determines the direction the ship is facing based on speeds.
// 0 = N, 1 = ne, 2 = e, 3 = se, 4 = s, 5 = sw, 6 = w, 7 = nw
int tempDir = 0;
if( dx == 0 && dy < 0){
// north
tempDir = 0;
} else if(dx == 0 && dy > 0){
// south
tempDir = 4;
} else if(dx > 0 && dy == 0){
// east
tempDir = 2;
} else if(dx > 0 && dy < 0){
// ne
tempDir = 1;
} else if( dx > 0 && dy > 0) {
// se
tempDir = 3;
} else if(dx < 0 && dy == 0){
// west
tempDir = 6;
} else if (dx < 0 && dy < 0){
//northWest
tempDir = 7;
} else if(dx < 0 && dy > 0){
//south west
tempDir = 5;
}
return tempDir;
}
提前感谢您的帮助!
编辑:我认为这是一个硬件问题。转换到ASDW控件而不是箭头键解决了问题。