Create the ScrollingBackground class. TODO: Optimize!

This commit is contained in:
Jan Philipp Timme 2014-11-25 15:18:11 +01:00
parent 14a8e469e0
commit 3fbff7890c
2 changed files with 63 additions and 31 deletions

View File

@ -0,0 +1,61 @@
package de.teamteamteam.spacescooter.background;
import java.awt.Graphics2D;
import de.teamteamteam.spacescooter.utility.GameConfig;
public class ScrollingBackground extends Background {
/**
* Speed the background scrolls through with.
*/
private int scrollingSpeed;
/**
* Internal offset counter to determine how much the Background scrolled.
*/
private int offset;
/**
* Default constructor.
*/
public ScrollingBackground(int x, int y) {
super(x, y);
this.offset = 0;
}
/**
* Set the scrolling speed to use for this Background.
*/
public void setScrollingSpeed(int scrollingSpeed) {
this.scrollingSpeed = scrollingSpeed;
}
/**
* Apply the scrolling effect by updating an internal offset counter.
* Reset it when we scrolled for one image length.
*/
public void update() {
this.offset += this.scrollingSpeed;
if(Math.abs(this.offset) > this.getImage().getWidth()) {
this.offset += this.getImage().getWidth();
}
}
/**
* Paint the Background. Concatenate the image if necessary, but still try
* to save ressources.
* TODO: Huge performance improvements using the tons of param version of drawImage!
*/
public void paint(Graphics2D g) {
int i = 0;
int wWidth = GameConfig.windowWidth;
while((i*this.getImage().getWidth()+this.offset) < wWidth) {
g.drawImage(this.getImage(), (i*this.getImage().getWidth()+this.offset), this.getY(), null);
i++;
}
}
}

View File

@ -1,46 +1,17 @@
package de.teamteamteam.spacescooter.background; package de.teamteamteam.spacescooter.background;
import java.awt.Graphics2D;
/** /**
* The StarBackground of the first level * The StarBackground of the first level
*/ */
public class StarBackground extends Background { public class StarBackground extends ScrollingBackground {
private int y;
/** /**
* Constructor for the background * Constructor for the background
*/ */
public StarBackground(int x, int y) { public StarBackground(int x, int y) {
super(x, y); super(x, y);
this.y = y;
this.setImage("images/starbackground.png"); this.setImage("images/starbackground.png");
} this.setScrollingSpeed(-2);
/**
* offset in x-direction for the painting
*/
private int offset = 0;
/**
* standart update method
*/
public void update() {
this.offset -= 2;
//System.out.println(this.offset);
if(Math.abs(this.offset) > this.getImage().getWidth()) {
this.offset += this.getImage().getWidth();
}
}
/**
* standart paint method
*/
public void paint(Graphics2D g) {
g.drawImage(this.getImage(), (0+this.offset), this.y, null);
g.drawImage(this.getImage(), (this.getImage().getWidth()+this.offset), this.y, null);
g.drawImage(this.getImage(), (2*this.getImage().getWidth()+this.offset), this.y, null);
} }
} }