Issue with my code for moving an image - java

Hi I am new to making games, and I am working on one for a project. My code however does not make the Ship image move. Can someone help with a reasonable and simple explanation? Maybe even explain how to do this a bit simpler?
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
import java.awt.geom.*;
import java.util.Random;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class SpaceJam extends JPanel implements ActionListener
{
private Timer time;
private ImageIcon Ship = new ImageIcon("Spaceship.PNG");
private ImageIcon Back = new ImageIcon("background.PNG");
private ImageIcon Test = new ImageIcon("test.PNG");
private int x, y, dx, dy;
private Image CurrentImage = Ship.getImage();
public SpaceJam()
{
addKeyListener(new AL());
setFocusable(true);
x = 100;
y = 100;
dx = 0;
dy = 0;
time = new Timer(100, this);
time.start();
}
public void actionPerformed(ActionEvent e)
{
repaint();
move();
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(Back.getImage() ,0,0,null);
g2d.drawImage(CurrentImage, x, y, null);
}
public void move()
{
x += dx;
y += dy;
}
public class AL extends KeyAdapter
{
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT)
{
dx = 5;
move();
}
if (key == KeyEvent.VK_LEFT)
{
dx = -5;
move();
}
}
}
}

Related

Java TSM AdjustCapsLockLEDForKeyTransitionHandling

I am trying to capture up,down,right,left keys from KeyEvent, and I am getting following message when I press a key:
2021-06-05 00:46:11.176 java[47646:1823153] TSM AdjustCapsLockLEDForKeyTransitionHandling - _ISSetPhysicalKeyboardCapsLockLED Inhibit
This is my code:
Character.java
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class Character {
private int dx;
private int dy;
private int x;
private int y;
private String imageLocation;
private Image image;
private boolean moveable;
public Character(int x, int y, String imgLoc, boolean m){
this.x = x;
this.y = y;
imageLocation = imgLoc;
ImageIcon ii = new ImageIcon(this.getClass().getResource(imageLocation));
image = ii.getImage();
moveable = m;
}
public void move() {
if(moveable){
x += dx;
y += dy;
}
}
public boolean moveable(){
return moveable;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return image;
}
public void keyPresed(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT){
System.out.println("left key pressed");
dx = -1;
}
if(key == KeyEvent.VK_RIGHT){
dx = 1;
}
if(key == KeyEvent.VK_UP){
dy = -1;
}
if(key == KeyEvent.VK_DOWN){
dy = 1;
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 0;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 0;
}
if (key == KeyEvent.VK_UP) {
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
}
}
** ADDED: **
Lounge.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Lounge extends JPanel implements ActionListener{
private Timer timer;
private Player player;
public Lounge(){
//addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.BLACK);
setDoubleBuffered(true);
player = new Player(1000, 40);
timer = new Timer(5, this);
timer.start();
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(player.getImage(), player.getX(), player.getY(), this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
player.move();
repaint();
}
private class TAdapter extends KeyAdapter{
public void keyReleased(KeyEvent e){
player.keyReleased(e);
}
public void keyPressed(KeyEvent e){
player.keyReleased(e);
}
}
}
Main.java
import javax.swing.JFrame;
public class Main extends JFrame{
public Main(){
add(new Lounge());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1280,720);
setLocationRelativeTo(null);
setTitle("Be My Guest");
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}
I am using Visual Studio Code on MacBook pro 2017
Please help me!
I think the problem is with the Caps-Lock key being pressed initially, I found a similar question over here
Another problem I found is that The method keyPressed is spelt wrongly as keyPresed that may cause some issues also

console displays error: class, interface, or enum expected package ball; on run. How do I fix it?

I am trying to create a mini tennis game. I am still a Java beginner and to make the program more organized I tried to create a package of each java file. Once I added the package extension and try to run the program the console displays error: class, interface, or enum expected on both the ball and racquet packages. How do I solve this problem?
/*This is Package minitennis*/
package minitennis;
package ball;
package racquet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Game extends JPanel {
Ball ball = new Ball(this);
Racquet racquet = new Racquet(this);
public Game() {
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
racquet.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
racquet.keyPressed(e);
}
});
setFocusable(true);
}
private void move() {
ball.move();
racquet.move();
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
ball.paint(g2d);
racquet.paint(g2d);
}
public void gameOver() {
JOptionPane.showMessageDialog(this, "Game Over", "Game Over", JOptionPane.YES_NO_OPTION);
System.exit(ABORT);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Mini Tennis");
Game game = new Game();
frame.add(game);
frame.setSize(300, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.move();
game.repaint();
Thread.sleep(10);
}
}
/*This is Package ball*/
package ball;
package minitennis;
package racquet;
import java.awt.Graphics2D;
import java.awt.Rectangle;
public class Ball {
private static final int DIAMETER = 30;
int x = 0;
int y = 0;
int xa = 1;
int ya = 1;
private Game game;
public Ball(Game game) {
this.game= game;
}
void move() {
if (x + xa < 0)
xa = 1;
if (x + xa > game.getWidth() - DIAMETER)
xa = -1;
if (y + ya < 0)
ya = 1;
if (y + ya > game.getHeight() - DIAMETER)
game.gameOver();
if (collision()){
ya = -1;
y = game.racquet.getTopY() - DIAMETER;
}
x = x + xa;
y = y + ya;
}
private boolean collision() {
return game.racquet.getBounds().intersects(getBounds());
}
public void paint(Graphics2D g) {
g.fillOval(x, y, DIAMETER, DIAMETER);
}
public Rectangle getBounds() {
return new Rectangle(x, y, DIAMETER, DIAMETER);
}
}
/*This is package racquet*/
package racquet;
package minitennis;
package ball;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
public class Racquet {
private static final int Y = 330;
private static final int WIDTH = 60;
private static final int HEIGHT = 10;
int x = 0;
int xa = 0;
private Game game;
public Racquet(Game game) {
this.game = game;
}
public void move() {
if (x + xa > 0 && x + xa < game.getWidth() - WIDTH)
x = x + xa;
}
public void paint(Graphics2D g) {
g.fillRect(x, Y, WIDTH, HEIGHT);
}
public void keyReleased(KeyEvent e) {
xa = 0;
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT)
xa = -1;
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
xa = 1;
}
public Rectangle getBounds() {
return new Rectangle(x, Y, WIDTH, HEIGHT);
}
public int getTopY() {
return Y;
}
}

Rotating images using the arrow keys

I am trying to make a racing game which uses the arrow keys to move the car(which is a image). When I click the left arrow key I want the image to rotate a certain amount of degrees to show that the car is turning. For some reason the car isn’t turning when the left arrow key is clicked and isn’t showing any error messages either. I would appreciate any help that you can give and thanks in advance!
//GameClass:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.MemoryImageSource;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
public class Game extends JPanel implements KeyListener {
private Image image;
BufferedImage images;
private Image image2;
private int x1, y1, velx = 0, vely = 0;
ImageIcon I2;
private Graphics2D g2;
public Game() {
x1 = 100;
y1 = 100;
}
public void paint(Graphics g) {
ImageIcon I = new ImageIcon("track.jpg");
image = I.getImage();
I2 = new ImageIcon("RedCar.png");
image2 = I2.getImage();
g.drawImage(image, 0, 0, null);
g.drawImage(image2,x1,y1,25,14,null);
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
try {
File url = new File("RedCar.png");
images = ImageIO.read(url);
}
catch(Exception r) {
r.printStackTrace();
}
Graphics g = images.getGraphics();
Graphics2D g2d = (Graphics2D)g;
g2d.rotate(Math.toRadians(15));
}
repaint();
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
x1 += 5;
velx = 1;
vely = 0;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
y1 -= 5;
velx = 0;
vely = -1;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
y1 += 5;
velx = 0;
vely = 1;
}
}
#Override
public void keyReleased(KeyEvent e) {
vely = 0;
velx = 0;
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
//GameDemo Class:
import javax.swing.*;
public class GameDemo {
public static void main(String[] args) {
Game game = new Game();
JFrame frame = new JFrame();
frame.setTitle("The Race");
frame.setSize(600, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(game);
frame.addKeyListener(game);
frame.setResizable(false);
}
}

My bullet is not being fired when i press the space bar

i'm teaching myself to program in java, and i have decided to make an space invader game. i got my ship moving in any direction, but i have a problem with my bullet being fired. now i know that my y-coordinate of the bullet are being updated every time my ship moves, but it is not firing. I need someone to help me get it to fire if possible. any help is welcome.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Panel extends JPanel implements KeyListener, ActionListener{
private int x;
private int y;
private int dx;
private int dy;
int bx;
int by;
Rectangle bullet;
Timer timer;
private Image image;
public Panel() {
timer = new Timer(30, this);
setBackground(Color.black);
addKeyListener(this);
setFocusable(true);
timer.start();
x=130;
y=430;
bx=xPost()+55;
by=yPost();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
ImageIcon ii= new ImageIcon("C:\\Users\\TriZam\\workspace\\LearningSprite\\ship.png");
image=ii.getImage();
g.drawImage(image, x, y, this);
doDrawing(g);
}
public void move(){
// thhis method will be placed inside the interferance ActionPerformed in order to move the ship and bullet
x += dx;
y += dy;
bx += dx;
by += dy;
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -3;
if (x<=-25){
dx=0;
}
}
if (key == KeyEvent.VK_RIGHT) {
dx = 3;
if (x>=380 ){
dx=0;
}
}
if (key == KeyEvent.VK_UP) {
dy = -3;
if (y<=0 ){
dy=0;
}
}
if (key == KeyEvent.VK_DOWN) {
dy = 3;
if (y>=430 ){
dy=0;
}
}
if(key ==KeyEvent.VK_SPACE){
// bullet shooting and as you can see the y coordinate updates but bullet not moving.
bullet.y--;
System.out.println(bullet.y--);
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 0;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 0;
}
if (key == KeyEvent.VK_UP) {
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent arg0) {
move();
repaint();
}
int yPost(){
return y;
}
int xPost(){
return x;
}
void doDrawing(Graphics g) {
bullet = new Rectangle(bx, by, 10, 10);
g.setColor(Color.white);
g.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
}
}
This is the main class
import javax.swing.JFrame;
public class MainClass extends JFrame {
private int FrameWidth;
private int FrameHeigh;
private Panel panel;
public MainClass(int width, int height ) {
panel= new Panel();
this.FrameWidth=width;
this.FrameHeigh=height;
setSize(FrameWidth,FrameHeigh);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(panel);
setVisible(true);
}
public static void main(String[] args) {
MainClass m= new MainClass(500, 600);
}
}
create the bullet once ; not inside paint and drawing - inside the constructor;
move this out of
void doDrawing(Graphics g) {
--> remove this from here and into the constructor --> bullet = new Rectangle(bx, by, 10, 10);
also when you update the location of the bullet dont use bx, by and separate variables; just do
bullet.x=....new location
bullet.y=....new location
Inside your key pressed space event, you should create an instance of a bullet. As of right now, you have a member variable Bullet; however it is null since it's never been initialized. That being said, you'll also want to move your bullet--this should be done in your move function.
I see that you have a bx, by, which I'm assuming is suppose to be the bullet's x and y position. However, the rectangle's coordinates never update. Instead of incrementing bx and by, update the rectangle (You'll also want to repaint the rectangle).

Lag in simple side scrolling game in Java

I recently built my first simple side scrolling game in java, but I'm experiencing some lag and I don't know why. When I move my character sideways it seems to be changing speed, most of the time going fast but sometimes slowing down. It makes the feel of the game very odd. I hope someone can point me in the right direction here, I'll post my classes below:
Main Class:
public class MainGame {
public static void main(String[] args) {
Frame frame = new Frame();
}
}
Frame Class:
import javax.swing.JFrame;
public class Frame extends JFrame{
public Frame(){
add(new Board());
setTitle("2-D Test Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800,325);
this.setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
}
}
Board Class:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Board extends JPanel implements ActionListener{
private Player p;
private Timer timer;
private Image background;
public Board(){
super();
p = new Player();
addKeyListener(new ActionListener());
setFocusable(true);
ImageIcon i = new ImageIcon("C:/test.png");
background = i.getImage();
timer = new Timer(5,this);
timer.start();
}
public void actionPerformed(ActionEvent arg0) {
p.move();
repaint();
}
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(background,p.nx,0,null);
g2d.drawImage(p.getImage(), 350, p.getY(), null);
}
private class ActionListener extends KeyAdapter{
public void keyReleased(KeyEvent e){
p.keyReleased(e);
}
public void keyPressed(KeyEvent e){
p.keyPressed(e);
}
}
}
Player Class:
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Player {
private Image img;
int x,y,dx,dy,nx;
long time;
private final int SPEED = 2;
private final int GRAV = 1;
boolean left,right,isJumping;
public Player(){
ImageIcon i = new ImageIcon("C:/plager.png");
img = i.getImage();
x = 350;
y = 160;
dx = 0;
dy = 0;
nx = 0;
left = false;
right = false;
isJumping = false;
}
public void move(){
x += dx;
nx = (nx-dx);
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public Image getImage(){
return img;
}
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_LEFT){
left = false;
if(right){
dx = SPEED;
}else{
dx = 0;
}
}else if(code == KeyEvent.VK_RIGHT){
right = false;
if(left){
dx = -SPEED;
}else{
dx = 0;
}
}
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_LEFT){
left = true;
dx = -SPEED;
}else if(code == KeyEvent.VK_RIGHT){
right = true;
dx = SPEED;
}
}
}
Timer does not have a real time guarantee. So, you should calculate the time difference from the last time move was called and multiply that by the amount you are moving. It will make the numbers smaller so I would add another const to make it larger. It's actually better get the time delta in actionPerformed (or another process method) and pass it to all of the process or move methods so everything moves using the same time delta.

Categories