我被导弹部分困住了。当fire()
发生时,如何在Missile.java
类中添加方法Player
(来自keyPressed
)。一旦我按下太空,导弹射击并添加到导弹物体的ArrayList。但它没有发生。
private ArrayList<Missilies> missilies;
public Player (MainClass mc){
url = mc.getDocumentBase();
player = mc.getImage(url,"spaceship1.png");
}
public void paint(Graphics g, MainClass mc){
g.drawImage(player, x, y, mc);
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()){
case KeyEvent.VK_SPACE:{
// fire a missile;
missilies.add(new Missilies(x, y));
ArrayList ms = (Missilies).
missilies.add(new Missilies(getX(), getY()));
break;
}
这里是导弹类
public class Missilies {
// New missile object ////////
public Missilies(int x, int y){
this.x=x;
this.y=y;
visible=true;
}
// Moving missiles ////////
public void update(MainClass mc, Player p){
x +=missile_speed;
if (x>mc.getWidth())
visible = false;
}
// Painting ////////
public void paint(Graphics g, MainClass mc, Player p) {
for (int i = 0; i < missilies.size(); i++ ) {
Missilies m = (Missilies) missilies.get(i);
g.drawImage(missile, p.getX(), p.getY(), mc);
}
}
// Firing new missile ///////////
public void fire(Player p){
missilies.add(new Missilies(p.getX(), p.getY()));
}
// Action performed //////////
public void action(MainClass mc, Player p){
for (int i = 0; i < missilies.size(); i++) {
Missilies m = (Missilies) missilies.get(i);
if (visible == true)
update(mc, p);
else missilies.remove(i);
}
}
}
主要课程
public void init()
{
setSize(800, 600);
p = new Player(this);
e = new Enemy(this);
}
{
while(running)
{
repaint();
p.update(this);
e.update(this, p);
try
{
Thread.sleep(20);
}
catch(InterruptedException e)
{
System.out.println("Error has occured");
}
}
}
public void update(Graphics g){
dbImage = createImage(800,600);
dbg = dbImage.getGraphics();
paint(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paint(Graphics g){
//g.setColor(Color.BLACK);
p.paint(g, this);
e.paint(g, this);
}
}
答案 0 :(得分:0)
欢迎使用Stack Overflow!
针对您的问题的一些建议 - 请务必清理您发布的代码并仅发布相关部分,因此很难阅读这样的混乱代码。正如Marc B所说,很难说出你实际要问的是什么,所以请在你的问题中说清楚并告诉我们你已经尝试过的事情。
据我所知,您无法从keyPressed事件处理程序调用Missilies.fire(sic)方法。让我们分解一下,因为你需要做三件事:
Missilies newMissile = new Missilies(x,y);
fire
:newMissile.fire(this);
missilies.add(newMissile);
再一次,阅读你的代码真的很难,所以请大家多多提一下我的建议。请尽量清理问题!
编辑:根据您上面关于NullPointerException的评论说明,问题是什么更清楚:您没有初始化您的missilies ArrayList!您应该确保在使用之前初始化每个对象。您的missilies = new ArrayList<Missilies>();
函数中需要public Player (MainClass mc)
这样的行。我不打算通过你的所有代码,但你应该检查你是否已经初始化了所有其他对象。