这段代码应该阻止一个对象通过它,如果一个对象击中它,则使它成为必须等待1秒才能再次与之交互。我认为最好的地方,但计时器将在keylistener之后,但当我尝试将if语句放下时,它只是出现了一个错误,即使它似乎是完整的。
我该怎么做才能解决这个问题?有没有更好的方法来做到这一点?
我将问题陈述放在中间,并在if语句的开头和结尾添加了注释行。谢谢你的帮助。
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
public class Imject {
int x = 30;
int y = 30;
int xa = 0;
int ya = 0;
private CrcGame Game;
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W)
if (collision()){
ya = 0;
y =- y;
}
else {ya = 1;
}
if (e.getKeyCode() == KeyEvent.VK_S)
if (collision()){
ya = 0;
}
else {ya = -1;
}
if (e.getKeyCode() == KeyEvent.VK_A)
if (collision()){
xa = 0;
}
else {xa = 1;
}
if (e.getKeyCode() == KeyEvent.VK_D)
if (collision()){
xa = 0;
}
else {xa = -1;
}
}
public void keyReleased(KeyEvent e) {
ya = 0;
xa = 0;
}
//Starts
if (collision()){
}
//Ends
void move() {
if (x + xa > 0)
x = x + xa;
if (y + ya > 0)
y = y + ya;
}
public Imject(CrcGame Game) {
this.Game= Game;
}
private boolean collision() {
return Game.player.getBounds().intersects(getBounds());
}
public void paint(Graphics2D g) {
g.fillRect(x, y, 100, 20);
}
public Rectangle getBounds() {
return new Rectangle(x, y, 100, 20);
}
}
答案 0 :(得分:0)
你的问题if语句不在函数中,它只是坐在课堂上。您需要将其移动到您的一种方法中。尝试结合移动功能和碰撞检查。
void move() {
if (x + xa > 0)
x = x + xa;
if (y + ya > 0)
y = y + ya;
}
if (collision()){
}
}