Hallo, ich programmiere momentan ein kleines Spiel.
Hier noch einmal meine Hilfestellung. Ursprünglich waren meine Tipps bereits hier zu finden.
https://www.java-forum.org/thema/png-als-spieler-im-fenster-anzeigen.190830/#post-1244334
Zum Testen die ducky.jar.
Die Büsche bewegen sich von Rechts nach links. Ducky kann mittels 'SPACE' springen. Mit Cursor links und rechts bremsen oder beschleunigen. Bei einer Kollision wir
collision auf der Konolse ausgegeben.
Wie beim letzten mal erwähnt: Kopiere den Code, starte ihn und versuche ihn zu verstehen.
Fragen dazu kannst du gerne hier posten.
Momentan habe ich nur das Grundgerüst, sodass mir alle wichtigen Teile des Spiels angezeigt werden (Spieler, Hindernisse, Hintergrund). Als nächstes würde ich gerne die Bewegungen realisieren
Du solltest zuerst immer mit dem Gameloop anfangen. Wie gesagt: Verwende meinen Beispielcode und baue darauf dein Spiel auf.
Der Code hat ein
großes Verbesserungspotential. Er verwendet aber viele Grundsätze die bei der Spieleprogrammierung essentiell sind.
Ich bin absolut keine Spieleentwicklerin, aber ich glaube in den meisten Ansätzen bewegen sich Büsche nicht, sondern nur die Figur und die View (und möglicher Weise andere Figuren/Objekte wie Gegner und herunterfallende Boosts).
Wenn die Büsche Hindernisse sind ( kein Hintergrund ), dann müssen sie sich bewegen. Für die Kollisionserkennung notwendig. In meinem Beispielcode verwende ich die Klasse
ObstacleLine, die die Buschbewegung realisiert.
Hier nun der Code zum Testen:
[CODE lang="java" title="StartDuckyGame" highlight="5,6,9,15,16"]import javax.swing.JFrame;
public class StartDuckGame {
public static void main(String[] args) {
System.setProperty("sun.java2d.opengl", "true"); // aktiviere Open GL
ImageLoader.loadImages(DuckyGame.names, "png"); // lade die notwendigen Bilder
JFrame frame = new JFrame("DuckyRun");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DuckyGame game = new DuckyGame();
frame.add(game);
frame.pack();
frame.setResizable(false);
frame.setLocation(10, 10);
frame.setVisible(true);
frame.addKeyListener(game.getKeyBoard()); // gib dem Fenster das Keyboard
game.start(); // starte das Spiel
}
}[/CODE]
[CODE lang="java" title="DuckyGame" highlight="18,21,38-52,58-61,67-69,74-82,100-104"]import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
@SuppressWarnings("serial")
public class DuckyGame extends JComponent implements Runnable {
public final static int WIDTH = 600;
public final static int HEIGHT = 400;
public final static String[] names = { "diddyDuck", "obstacle1", "obstacle2" };
public final static int DUCKY = 0;
public final static int BUSH_A = 1;
public final static int BUSH_B = 2;
private int horizont = 175;
private Duck duck;
private float bushSpeed = 1.1f;
private float duckSpeed = 3 * bushSpeed / 4;
private ObstaclesLine bushes = new ObstaclesLine(horizont, WIDTH);
private boolean running = false;
private Thread aniamtor = null;
public DuckyGame() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
initGame();
}
private void drawBackGround(Graphics g) {
g.setColor(new Color(184, 233, 236));
g.fillRect(0, 0, WIDTH, HEIGHT / 2);
g.setColor(new Color(135, 121, 74));
g.fillRect(0, HEIGHT / 2, WIDTH, HEIGHT / 2);
}
public KeyAdapter getKeyBoard() {
return new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
duck.setSpeed(-duckSpeed);
if (key == KeyEvent.VK_RIGHT)
duck.setSpeed(duckSpeed);
}
@Override
public void keyReleased(KeyEvent e) {
duck.setSpeed(0);
if (e.getKeyCode() == KeyEvent.VK_SPACE)
duck.jump();
}
};
}
private void initGame() {
duck = new Duck(names[DUCKY], 50, 60);
duck.setPos(100, horizont);
bushes.create(new String[] { names[BUSH_A], names[BUSH_B] }, 50, 60);
bushes.setSpeed(-bushSpeed);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawBackGround(g);
bushes.draw(g);
duck.draw(g);
}
@Override
public void run() {
while (running) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
updateGame();
repaint();
}
}
public void start() {
stop();
running = true;
aniamtor = new Thread(this);
aniamtor.start();
}
private void stop() {
running = false;
while (aniamtor != null && aniamtor.isAlive())
;
aniamtor = null;
}
private void updateGame() {
duck.move();
bushes.move();
if (bushes.isCollision(duck)) {
System.out.println("collision");
}
}
}
[/CODE]
[CODE lang="java" title="Sprite"]import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
public class Sprite {
private String name;
private Image image;
protected float x; // x Position
protected float y; // y Position
protected float dx; // Geschwindigkeit x Richtung
protected float dy;// Geschwindigkeit y Richtung
private Rectangle bounds;
private int shrinkBounds = 0;
public Sprite(String name, int width, int height) {
this.name = name;
image = ImageLoader.getScaledImage(name, width, height);
}
public void draw(Graphics g) {
if (image != null)
g.drawImage(image, (int) x, (int) y, null);
}
public Rectangle getBoundingBox() {
if (bounds == null)
bounds = new Rectangle(0, 0, image.getWidth(null) - 2 * shrinkBounds,
image.getHeight(null) - 2 * shrinkBounds);
bounds.x = (int) (x + shrinkBounds);
bounds.y = (int) (y + shrinkBounds);
return bounds;
}
public int getHeight() {
return image.getHeight(null);
}
public int getWidth() {
return image.getWidth(null);
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public boolean isCollision(Sprite s) {
return getBoundingBox().intersects(s.getBoundingBox());
}
public void move() {
x += dx;
y += dy;
}
public void setShrinkBounds(int shrinkBounds) {
if (shrinkBounds < 0)
return;
this.shrinkBounds = shrinkBounds;
bounds = null;
}
public void setPos(int x, int y) {
this.x = x;
this.y = y;
}
public void setSpeed(float dx, float dy) {
this.dx = dx;
this.dy = dy;
}
@Override
public String toString() {
return String.format("%s <%.2f,%.2f>", name, x, y);
}
}
[/CODE]
[CODE lang="java" title="Duck" highlight="21-29, 13-15"]public class Duck extends Sprite {
private float jumpHigh = 0;
private float jumpSpeed = -.9f;
private int jumpMax = 80;
private boolean jumping = false;
public Duck(String name, int width, int height) {
super(name, width, height);
setShrinkBounds(width / 5);
}
public void jump() {
jumpHigh = 0;
jumping = true;
jumpSpeed = -Math.abs(jumpSpeed);
}
@Override
public void move() {
super.move();
if (jumping) {
if (Math.abs(jumpHigh) > jumpMax)
jumpSpeed = -jumpSpeed;
if (jumpHigh >= 0 && jumpSpeed > 0)
jumping = false;
else {
jumpHigh += jumpSpeed;
y += jumpSpeed;
}
}
}
public void setSpeed(float speed) {
this.dx = speed;
}
}[/CODE]
[CODE lang="java" title="ObstaclesLine" highlight="17-26,30-34,43-48,52,53"]import java.awt.Graphics;
import java.util.Random;
public class ObstaclesLine {
private final static Random rnd = new Random(System.currentTimeMillis());
private int horziont;
private int width;
private int minDistance = 160;
private Sprite[] obstacle;
public ObstaclesLine(int horizont, int width) {
this.horziont = horizont;
this.width = width;
}
public void create( String[] name, int width, int height) {
int num = this.width / minDistance;
int pos = this.width;
obstacle = new Sprite[num];
for (int i = 0; i < obstacle.length; i++) {
obstacle
= new Sprite(name[i % name.length], width, height);
obstacle.setPos(pos, horziont);
obstacle.setSpeed(-.3f, 0);
obstacle.setShrinkBounds(width/5);
pos += minDistance + rnd.nextInt(50);
}
}
public boolean isCollision(Sprite s) {
for (int i = 0; i < obstacle.length; i++) {
if (obstacle.isCollision(s))
return true;
}
return false;
}
public void draw(Graphics g) {
for (int i = 0; i < obstacle.length; i++)
obstacle.draw(g);
}
public void move() {
for (int i = 0; i < obstacle.length; i++) {
obstacle.move();
int w = obstacle.getWidth();
if (obstacle.getX() < -w)
obstacle.setPos(width+ minDistance, horziont);
}
}
public void setSpeed(float speed) {
for (int i = 0; i < obstacle.length; i++)
obstacle.setSpeed(speed, 0);
}
}
[/CODE]
[CODE lang="java" title="ImageLoader" highlight="8-9"]import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javax.imageio.ImageIO;
public class ImageLoader {
public static String sourceDir = "./src/"; // Eclipse source folder
public static String resourceDir = "resources/"; // Hier den Pfad anpassen
private final static HashMap<String, Image> images = new HashMap<String, Image>();
public static Image get(String name) {
return images.get(name);
}
public static Image getScaledImage(String name, int width, int height) {
Image image = get(name);
if (image == null)
return null;
if (image.getWidth(null) != width || image.getHeight(null) != height) {
images.remove(name);
image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
images.put(name, image);
}
return image;
}
public static void loadImages(String[] nameImages, String type) {
for (String name : nameImages) {
String fileName = resourceDir + name + "." + type;
File file = new File(sourceDir + fileName);
Image image = null;
System.out.println(fileName);
try {
if (file.exists())
image = ImageIO.read(file);
else
image = ImageIO.read(ClassLoader.getSystemResource(fileName));
if (image != null)
images.put(name, image);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
[/CODE]