Reputation: 9
For my computer science class, I was asked to create a game. Everything was going smoothly until I came upon the issue of mouse input. What I am trying to accomplish is to click a mouse at a certain position in the JFrame, then have a bullet initialize at my character's spot and shoot towards the point of the mouse. I already understand how to use trig in order to get the bullet to shoot at that angle. The problem is that when I shoot a bullet after clicking the mouse, the x and y positions of my character are not updated to the bullet, meaning that the bullet always initializes in the same place. Here are code segments in which I believe are causing the problem.
public void mousePressed(MouseEvent e)
{
handler.addObject(new Bullet("res\\Fireball.png",x,y + ,ID.BasicEnemy,handler));
}
public void mouseReleased(MouseEvent e)
{
}
public void tick()
{
x+=velX;
y+=velY;
x = Game.clamp(x,0,Game.WIDTH-40);
y = Game.clamp(y,0,Game.HEIGHT-40);
collision();
}
From what I gathered through research, the reason why the x and y in mousePressed() method is not updating is because the mouse event is in a different thread than my tick. I'm a little new to java game programming and I was wondering if there would be anyone out there who could give me explicit suggestions. The actual code of my game is very long, so I narrowed it down to the piece of code above.(I tried synchronized reserved word and volatile variables, but I might have implemented them wrong)
And if this helps, conversely, if I do this below, the bullet object never appears!
public void mousePressed(MouseEvent e)
{
press=true;
}
public void mouseReleased(MouseEvent e)
{
press=false;
}
public void tick()
{
x+=velX;
y+=velY;
x = Game.clamp(x,0,Game.WIDTH-40);
y = Game.clamp(y,0,Game.HEIGHT-40);
collision();
if (press)
handler.addObject(new Bullet("res\\Fireball.png",(int)x,(int)y ,ID.BasicEnemy,handler));
}
Upvotes: 0
Views: 39
Reputation: 285460
Here:
public void mousePressed(MouseEvent e) {
handler.addObject(new Bullet("res\\Fireball.png",x,y + ,ID.BasicEnemy,handler));
}
You never use the MouseEvent Point object, but seem to use an unchanging x and y value. Perhaps (hard to say) you want to use the x and y from the MouseEvent object:
public void mousePressed(MouseEvent e) {
handler.addObject(new Bullet("res\\Fireball.png", e.getX(), e.getY(),
ID.BasicEnemy, handler));
}
If this does not solve your problem, then consider creating and posting a Minimal, Complete, and Verifiable Example Program where you condense your code into the smallest bit that still compiles and runs, has no outside dependencies (such as need to link to a database or images), has no extra code that's not relevant to your problem, but still demonstrates your problem.
Upvotes: 2