Java 2D игра: анимация Cat Down не рендеринг во время движения внизJAVA

Программисты JAVA общаются здесь
Anonymous
Java 2D игра: анимация Cat Down не рендеринг во время движения вниз

Сообщение Anonymous »

Я строю 2D-игру Java (без каких-либо игровых двигателей), вдохновленную Pac-Man. В нем персонаж кошки перемещается и анимируется с использованием кадров Sprite для каждого направления (вверх, вниз, слева, справа).
Каждое направление имеет 6 кадров, загруженных из файлов .png .
Проблема заключается в том, что кошка движется правильно во всех направлениях, анимации для влево, влево, и вправо работает в том, что в порядке, однако, когда -то подходит. /> Шаги отладки. Kittydown 0.png, kittydown 1.png и т. Д. < /P>
import javax.swing.JFrame;

public class Main{
public static void main(String[] args) throws Exception{
//Creating the size of the window
int rowNum = 13;
int columnNum = 19;
int tileSize = 64;
int boardWidth = columnNum * tileSize;
int boardHeight = rowNum * tileSize;

JFrame window = new JFrame ("Cat-ch Fishy");
//window.setVisible(true);
window.setLocationRelativeTo(null); // setting the window at the center of teh screen
window.setResizable(false); // do not let the user resize the window.
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

CatchFishy catchFishyGame = new CatchFishy();//creating an instance of the JPanel
window.add(catchFishyGame);
window.pack();
window.setVisible(true);
}
}

import java.awt.*;
import java.awt.event.*;
import java.util.HashSet;
import java.util.Random;
import javax.swing.*;
import java.awt.Image;

public class CatchFishy extends JPanel {// inherits JPanel

class Block { // inner class to represent a block on the map, such as, wall, cat, etc.
int x; // positions of the block
int y;
int width; // size of the block
int height;
Image image; // the image to draw for this block

int startX; // the initial spawn position
int startY;

Block(Image image, int x, int y, int width, int height) {
this.image = image;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.startX = x;
this.startY = y;
}
}

enum Direction {
UP, DOWN, LEFT, RIGHT
}

// grid setup
// JPanel will have the same size as the window
private final int rowNum = 13;
private final int columnNum = 19;
private final int tileSize = 64; // each tile will be 64x64 pixels
private final int boardWidth = columnNum * tileSize;
private final int boardHeight = rowNum * tileSize;

// game background and wall image
private final Image bgImage;
private final Image wallImage;

// animation frames for the fish, cat, and dog
private final Image[] FishFrames = new Image[2];

private final Image[] DogUpFrames = new Image[6];
private final Image[] DogDownFrames = new Image[6];
private final Image[] DogLeftFrames = new Image[6];
private final Image[] DogRightFrames = new Image[6];

private final Image[] CatUpFrames = new Image[6];
private final Image[] CatDownFrames = new Image[6];
private final Image[] CatLeftFrames = new Image[6];
private final Image[] CatRightFrames = new Image[6];

// game object colletions
HashSet walls; // stores wall blocks
HashSet food; //stores food blocks
Block cat; // the player character
HashSet dogs; // the player enemy

// tile map representation: X = wall, C = cat, D = dog, space = empty
private String[] tileMap = {
"XXXXXXXXXXXXXXXXXXX",
"X X XX X XX X X",
"X XX XX X",
"X XXX XXX X",
"X X X XXCXX X X X",
"X X XXX X X",
" XXX XXX ",
"X X XXX X X",
"XX XXX XDXDX XXX XX",
"XX X D X XX",
"X XX XXXXX XX X",
"X X X",
"XXXXXXXXXXXXXXXXXXX"
};

// animation frame tracking
private int catFrameIndex = 0;
private int dogFrameIndex = 0;
private int fishFrameIndex = 0;
private long lastFrameTime = 0;
private final int frameDelay = 100; // animation delay in milliseconds (10 FPS)
private final int fishframeDelay = 300;

// constructor to set up game panel
CatchFishy() {//Creating a constructor
setPreferredSize(new Dimension(boardWidth, boardHeight)); // set panel size
setLayout(null); // no layout manager aka using absolute positioning

// load background and wall images
bgImage = new ImageIcon("Images/BG.png").getImage();
wallImage = new ImageIcon("Images/Wall.png").getImage();

// load animation frames for the cat and dog (6 frames per direction)
for (int i = 0; i < 6; i++) {
CatUpFrames = new ImageIcon("Images/KittyUp/KittyUp " + i + ".png").getImage();
CatDownFrames = new ImageIcon("Images/KittyDown/KittyDown " + i + " copy.png").getImage();
CatLeftFrames = new ImageIcon("Images/KittyLeft/KittyLeft " + i + ".png").getImage();
CatRightFrames = new ImageIcon("Images/KittyRight/KittyRight " + i + ".png").getImage();

DogUpFrames = new ImageIcon("Images/PuppyUp/PuppyUp " + i + ".png").getImage();
DogDownFrames = new ImageIcon("Images/PuppyDown/PuppyDown " + i + ".png").getImage();
DogLeftFrames = new ImageIcon("Images/PuppyLeft/PuppyLeft " + i + ".png").getImage();
DogRightFrames = new ImageIcon("Images/PuppyRight/PuppyRight " + i + ".png").getImage();
}
// load animation frames for the fish (2 frame loop)
for (int i = 0; i < 2; i++) {
FishFrames = new ImageIcon("Images/Fish/Fish " + i + ".png").getImage();
if (FishFrames == null) {
System.out.println("FishFrames " + i + " failed to load"); // checking to make sure
}
}

loadMap();
startFishAnimationTimer();
startCatAnimationTimer();
setupControls();

// testing to see if they show up
System.out.println(walls.size());
System.out.println(food.size());
}

public void loadMap() {
walls = new HashSet();
food = new HashSet();
dogs = new HashSet();

for (int r = 0; r < rowNum; r++) {
for (int c = 0; c < columnNum; c++) {
String row = tileMap[r];
char tileMapChar = row.charAt(c);

int x = c * tileSize;
int y = r * tileSize;

if (tileMapChar == 'X') { // block wall
Block wall = new Block(wallImage, x, y, tileSize, tileSize);
walls.add(wall);
} else if (tileMapChar == ' ') { // food
Block fish = new Block(FishFrames[fishFrameIndex], x, y, tileSize, tileSize);
food.add(fish);
} else if (tileMapChar == 'C') { // kitty cat
cat = new Block(CatRightFrames[0], x, y, tileSize, tileSize);
} else if (tileMapChar == 'D') { // dog
Block dog = new Block(DogRightFrames[0], x, y, tileSize, tileSize);
dogs.add(dog);
}
}
}
}

private void startFishAnimationTimer() {
Timer fishTimer = new Timer(fishframeDelay, new ActionListener() {
public void actionPerformed(ActionEvent e) {
fishFrameIndex = (fishFrameIndex + 1) % FishFrames.length;
for (Block fish : food) {
fish.image = FishFrames[fishFrameIndex];
}
repaint();
}
});
fishTimer.start();
}
private void startCatAnimationTimer() {
Timer catTimer = new Timer(150, new ActionListener() {
public void actionPerformed(ActionEvent e) {
catFrameIndex = (catFrameIndex + 1) % 6;
switch (catDirection) {
case UP: cat.image = CatUpFrames[catFrameIndex]; break;
case DOWN: cat.image = CatDownFrames[catFrameIndex]; break;
case LEFT: cat.image = CatLeftFrames[catFrameIndex]; break;
case RIGHT: cat.image = CatRightFrames[catFrameIndex]; break;
}
System.out.println("Animating: " + catDirection + " Frame: " + catFrameIndex);
repaint();
}
});
catTimer.start();
}

private Direction catDirection = Direction.RIGHT;

private void setupControls() {
//Cat Movement
getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("UP"), "catMoveUp");
getActionMap().put("catMoveUp", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
moveCat(Direction.UP);
}
});
getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("DOWN"), "catMoveDown");
getActionMap().put("catMoveDown", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
moveCat(Direction.DOWN);
}
});
getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("LEFT"), "catMoveLeft");
getActionMap().put("catMoveLeft", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
moveCat(Direction.LEFT);
}
});
getInputMap(WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("RIGHT"), "catMoveRight");
getActionMap().put("catMoveRight", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
moveCat(Direction.RIGHT);
}
});
}

private void moveCat(Direction dir) {
int dx = 0;
int dy = 0;
switch (dir) {
case UP: dy = -tileSize; break;
case DOWN: dy = tileSize; break;
case LEFT: dx = -tileSize; break;
case RIGHT: dx = tileSize; break;
}

int newX = cat.x + dx;
int newY = cat.y + dy;
Rectangle nextPos = new Rectangle(newX, newY, tileSize, tileSize);

for (Block wall : walls) {
if (nextPos.intersects(new Rectangle(wall.x, wall.y, tileSize, tileSize))) {
return; // if it hits wall it does not move through it
}
}
cat.x = newX;
cat.y = newY;
catDirection = dir;
System.out.println("cat direction " + catDirection); // checking directions (troubleshooting)

repaint();
}

// custom painting of the panel
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

// draw the background
g.drawImage(bgImage, 0, 0, null);

// draw all wall blocks
for (Block wall : walls) {
if (wall.image != null) {
g.drawImage(wall.image, wall.x, wall.y, wall.width, wall.height, null);
}
}

// draw all food blocks
for (Block fish : food) {
if (fish.image != null) {
g.drawImage(fish.image, fish.x, fish.y, fish.width, fish.height, null);
}
}

// draw the cat
if (cat != null && cat.image != null) {
g.drawImage(cat.image, cat.x, cat.y, cat.width, cat.height, null);
}

// draw all dog blocks
for (Block dog : dogs) {
if (dog != null && dog.image != null) {
g.drawImage(dog.image, dog.x, dog.y, dog.width, dog.height, null);
}
}
}

}


Подробнее здесь: https://stackoverflow.com/questions/796 ... oving-down

Вернуться в «JAVA»