Tracking multiple touch movement - java

I have a custom view which detects user touch and draws a circle when screen is touched. Different circles for different fingers.And circle is cleared when user removes the finger. Now i have to move the circle while moving the fingers.
i can only move 1 circle while moving fingers. IF i have more than 1 finger on screen, how can i move all the circle in the finger direction?
public boolean onTouchEvent(MotionEvent event) {
int pointerIndex = event.getActionIndex();
int pointerId = event.getPointerId(pointerIndex);
int maskedAction = event.getActionMasked();
switch (maskedAction){
case MotionEvent.ACTION_DOWN: {
Pointers pointer = new Pointers();
pointer.setX(event.getX(pointerIndex));
pointer.setY(event.getY(pointerIndex));
pointer.setPaint(getPaint());
pointersList.put(pointerId,pointer);
break;
}
case MotionEvent.ACTION_POINTER_DOWN: {
Pointers pointer = new Pointers();
pointer.setX(event.getX(pointerIndex));
pointer.setY(event.getY(pointerIndex));
pointer.setPaint(getPaint());
pointersList.put(pointerId,pointer);
break;
}
case MotionEvent.ACTION_MOVE:{
int size = event.getPointerCount();
Pointers point = pointersList.get(pointerId);
if (point != null) {
point.setX(event.getX(pointerIndex));
point.setY(event.getY(pointerIndex));
}
}
break;
case MotionEvent.ACTION_UP:{
pointersList.remove(pointerId);
}
case MotionEvent.ACTION_POINTER_UP: {
pointersList.remove(pointerId);
break;
}
case MotionEvent.ACTION_CANCEL:{
pointersList.remove(pointerId);
break;
}
}
invalidate();
return true;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int size = pointersList.size();
for(int i=0; i<size;i++){
Pointers point = pointersList.get(i);
if(point != null){
canvas.drawCircle(point.getX(),point.getY(),SIZE,point.getPaint());
}
}
}
Pointer Class
public class Pointers {
private float x,y;
private Paint paint;
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public Paint getPaint() {
return paint;
}
public void setPaint(Paint paint) {
this.paint = paint;
}
}

I think the problem is in the draw method.
From what I can tell pointerList is a Map that uses the pointer ID as the key.
In the draw method you're trying to get all the pointer that have the key in the range 0 to total pointers - 1 which is incorrect. You're trying to get the pointers by index but they were stored by ID.
Try this:
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for(Map.Entry<Integer, Pointers> entry : pointersList.entrySet()){
Pointers point = entry.getValue();
canvas.drawCircle(point.getX(),point.getY(),SIZE,point.getPaint());
}
}

Related

LibGDX Flip 2D Sprite Animation

I have an animation that I want to play flipped if the user presses the 'A' key on their keyboard. The animation is facing right in the file and is played normally until I try to flip the texture.
This is what happens when I try to flip the texture when the player's direction has changed:
As you can see, the animation plays fine in the beginning but when I change the player's direction it alternates between the flipped frame and the unflipped frame.
This is my player class:
package unit22.game;
import java.util.ArrayList;
import unit22.core.Utils;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
public class Player {
private PlayerState state = PlayerState.STANDING;
private Direction direction = Direction.RIGHT;
private int x = 0, y = 0, width = 0, height = 0;
private PlayerInputProcessor inputProcessor;
private String name;
private ArrayList<Action> actions;
private Animation standingAnim;
private Animation movingAnim;
private float stateTime;
private SpriteBatch spriteBatch;
private Action currentAction;
private Animation currentAnimation;
public Player(String name, int x, int y, int width, int height) {
this.name = name;
setBounds(x, y, width, height);
if(getX() > 400) setDirection(Direction.LEFT);
this.actions = new ArrayList<Action>();
standingAnim = new Animation(0.06f, Utils.loadTextureAtlas("standing", "textures/characters/animations/" + name + "/").getRegions());
//movingAnim = new Animation(0.06f, Utils.loadTextureAtlas("moving", "textures/characters/animations/" + name + "/").getRegions());
stateTime = 0f;
spriteBatch = new SpriteBatch();
}
public void update() {
stateTime += Gdx.graphics.getDeltaTime();
switch(state) {
case STANDING:
if(currentAnimation != standingAnim)
currentAnimation = standingAnim;
break;
case MOVING:
if(currentAnimation != movingAnim)
currentAnimation = movingAnim;
break;
case ACTING:
Animation anim = new Animation(0.06f, Utils.loadTextureAtlas(currentAction.getName(), "textures/characters/animations/" + getName() + "/").getRegions());
if(currentAnimation != anim)
currentAnimation = anim;
break;
}
}
public void render() {
TextureRegion currentFrame = currentAnimation.getKeyFrame(stateTime, true);
if(getDirection() == Direction.LEFT) {
currentFrame.flip(true, false);
}
System.out.println("Direction: " + direction + ", Flipped: " + currentFrame.isFlipX());
spriteBatch.begin();
spriteBatch.draw(currentFrame, x, y, width, height);
spriteBatch.end();
}
public ArrayList<Action> getActions() {
return actions;
}
public void addAction(Action action) {
this.actions.add(action);
}
public void setActions(ArrayList<Action> actions) {
this.actions = actions;
}
public void setInputProcessor(PlayerInputProcessor inputProcessor) {
this.inputProcessor = inputProcessor;
}
public PlayerInputProcessor getInputProcessor() {
return inputProcessor;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Direction getDirection() {
return direction;
}
public PlayerState getState() {
return state;
}
public void setDirection(Direction direction) {
this.direction = direction;
}
public void setState(PlayerState state) {
this.state = state;
}
public int[] getBounds() {
return new int[] {x, y, width, height};
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public void setBounds(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
}
In my render method I am checking whether the player's direction is left and if it is then to flip the current animation frame.
This is how I am handling my input:
package unit22.screens;
import unit22.core.Game;
import unit22.core.Screen;
import unit22.game.Direction;
import unit22.game.Player;
import unit22.game.PlayerInputProcessor;
import com.badlogic.gdx.Gdx;
public class Playing extends Screen {
Player player;
public Playing(Game game, String name) {
super(game, name);
}
#Override
public void init() {
player = new Player("misaka", 100, 100, 188, 380);
player.setInputProcessor(new PlayerInputProcessor(player) {
#Override
public boolean keyTyped(char character) {
if(getPlayer().getX() <= 14) getPlayer().setX(15);
if(getPlayer().getX() + getPlayer().getWidth() >= 1024 - getPlayer().getWidth()) getPlayer().setX(1024 - getPlayer().getWidth() - 15);
if(character == 'a' || character == 'A') {
getPlayer().setX((int)(getPlayer().getX() - (900 * Gdx.graphics.getDeltaTime())));
if(getPlayer().getDirection() == Direction.RIGHT) {
getPlayer().setDirection(Direction.LEFT);
}
}
if(character == 'd' || character == 'D') {
getPlayer().setX((int)(getPlayer().getX() + (900 * Gdx.graphics.getDeltaTime())));
if(getPlayer().getDirection() == Direction.LEFT) {
getPlayer().setDirection(Direction.RIGHT);
}
}
return super.keyTyped(character);
}
});
getInputHandle().addProcessor(player.getInputProcessor());
}
#Override
public void render(float delta) {
super.render(delta);
player.update();
player.render();
}
}
I've been trying to figure this problem out for a couple of hours now and haven't made any progress. Any idea why this would be happening?
The problem is here:
if(getDirection() == Direction.LEFT) {
currentFrame.flip(true, false);
}
The flip method permanently flips the original TextureRegion that the Animation class is referencing. So you either need to make sure you flip it back each time after flipping and drawing it, or do this, which I think is simpler:
Never flip it but instead use a negative width when drawing it with SpriteBatch, like this:
boolean flip = (getDirection() == Direction.LEFT);
spriteBatch.draw(currentFrame, flip ? x+width : x, y, flip ? -width : width, height);
If somebody is still wondering, negating scaleX or scaleY works like a charm and does not hurt performance (like TextureRegion.flip does for example).
Example:
draw(region, x, y, originX, originY, width, float height,
(flip ? -1 : 1) * scaleX, float scaleY, float rotation);
I know that question is old but I think it is better solution
currentFrame = walkAnimation.getKeyFrame(stateTime, true);
if(!currentFrame.isFlipX())
currentFrame.flip(true, false);
batch.draw(currentFrame, 0,0,0,0);
I flip my animation sequence use the code below(in kotlin):
if (this.position <= 0f)
{
this.speed = - this.speed
this.position = 0.0f
this.runAnimation.keyFrames.forEach {
it.flip(true, false)
}
}else if(this.position >= SCREEN_WIDTH / SCALE - width)
{
this.speed = - this.speed
this.position = SCREEN_WIDTH / SCALE - width
this.runAnimation.keyFrames.forEach {
it.flip(true, false)
}
}
this.game.batch.begin()
this.game.batch.draw(currentFrame, this.position, 40f)
this.game.batch.end()
Every time you flip the sequence, make sure loop every frame and flip every one:
this.runAnimation.keyFrames.forEach { it.flip(true, false) }
and remember that, the frames are flipped forever, so if you want to return back, you should flip again(flip = true)!

Rectangle Wall collision in Java

I really could use some help in order to find a working solution for my game.
My game is almost done, but the walls in my game are still not working as they should.
I have tried to find a solution on the internet for this problem, but i still haven't found a simple way to stop a rectangle just before it will collide with a wall (another rectangle).
Right now i have implemented a collision detection between the player rectangle and the wall rectangle and then stopped it to move, but then it gets stuck inside a wall when it hits.
Want it to stop just before, so it still can move. The code i have done this with so far is here:
Pacman Class
public class Pacman {
private String pacmanup = "pacmanup.png";
private String pacmandown = "pacmandown.png";
private String pacmanleft = "pacmanleft.png";
private String pacmanright = "pacmanright.png";
private int dx;
private int dy;
private int x;
private int y;
private int width;
private int height;
private boolean visible;
private Image imageup;
private Image imagedown;
private Image imageleft;
private Image imageright;
public Pacman() {
ImageIcon i1 = new ImageIcon(this.getClass().getResource(pacmanup));
imageup = i1.getImage();
ImageIcon i2 = new ImageIcon(this.getClass().getResource(pacmandown));
imagedown = i2.getImage();
ImageIcon i3 = new ImageIcon(this.getClass().getResource(pacmanleft));
imageleft = i3.getImage();
ImageIcon i4 = new ImageIcon(this.getClass().getResource(pacmanright));
imageright = i4.getImage();
width = imageup.getWidth(null);
height = imageup.getHeight(null);
visible = true;
x = 270;
y = 189;
}
public int getDx() {
return dx;
}
public void setDx(int dx) {
this.dx = dx;
}
public int getDy() {
return dy;
}
public void setDy(int dy) {
this.dy = dy;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public Image getImageup() {
return imageup;
}
public Image getImagedown() {
return imagedown;
}
public Image getImageleft() {
return imageleft;
}
public Image getImageright() {
return imageright;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public boolean isVisible() {
return visible;
}
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
public void move() {
x += dx;
y += dy;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -2;
dy = 0;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 2;
dy = 0;
}
if (key == KeyEvent.VK_UP) {
dx = 0;
dy = -2;
}
if (key == KeyEvent.VK_DOWN) {
dx = 0;
dy = 2;
}
}
Here i have created a Rectangle getBounds method which i use to create an rectangle of the pacman and place an image over it.
Barrier class / Wall class
public class Barrier {
private String barrier = "barrier.png";
private int x;
private int y;
private int width;
private int height;
private boolean visible;
private Image image;
public Barrier(int x, int y) {
ImageIcon ii = new ImageIcon(this.getClass().getResource(barrier));
image = ii.getImage();
width = image.getWidth(null);
height = image.getHeight(null);
visible = true;
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public boolean isVisible() {
return visible;
}
public void setVisible(Boolean visible) {
this.visible = visible;
}
public Image getImage() {
return image;
}
public Rectangle getBounds() {
return new Rectangle(x, y, width, height);
}
This class also have the Rectangle getBounds class which i use to detect collision.
The last code i show is how i do the collision detection so far:
Code inside Board class
Rectangle r3 = pacman.getBounds();
for (int j = 0; j<barriers.size(); j++) {
Barrier b = (Barrier) barriers.get(j);
Rectangle r4 = b.getBounds();
if (r3.intersects(r4)) {
System.out.println("Wall hit");
pacman.setDx(0);
pacman.setDy(0);
}
}
Well, what i do, if there is a collision between r3 and r4, i gonna set Dx and Dy to 0.. what i want to find another solution so it detect for collision but i wont get stuck inside a wall, but i don't know how to :/
Hope someone will help.
There are two approaches you can follow. One is ugly but easier, the other one requires a deeper redesign of your classes.
1) Ugly/Simple Approach
In the ugly one, you keep moving your guy before doing the collision checks. Simply move your pacman back to the point where it was not stuck. You accomplish that by inverting the last directions used:
Code inside Board class
Change your reaction in case you find a collision: just walk the same distance, backwards.
if (r3.intersects(r4)) {
System.out.println("Wall hit, move back");
pacman.setDx(-pacman.getDx());
pacman.setDy(-pacman.getDy());
// Possibly need to call move() here again.
pacman.move();
break;
}
Ugly, but should work.
Not recommended to coding perfectionists with OCD and heart disease, though.
2) Redesign
In this approach, you test the position pacman will occupy before doing any actual moves. If that spot is not into any barrier, then perform the movement for real.
Code inside Pacman class
Add this method, so that you can check for collisions against the new bounds.
public Rectangle getOffsetBounds() {
return new Rectangle(x + dx, y + dy, width, height);
}
Code inside Board class
// Strip the call to pacman.move() prior to this point.
Rectangle r3 = pacman.getOffsetBounds(); // Check against the candidate position.
for (int j = 0; j<barriers.size(); j++) {
Barrier b = (Barrier) barriers.get(j);
Rectangle r4 = b.getBounds();
if (r3.intersects(r4)) {
System.out.println("Wall hit");
pacman.setDx(0);
pacman.setDy(0);
// Quit the loop. It's pointless to check other barriers once we hit one.
break;
}
}
// Now we're good to move only in case there's no barrier on our way.
pacman.move();
Particularly I prefer this approach, but it's up to you to pick the best one.

Failing to try to change an image when keypressed

I'm trying to make it so when I press down the right key a new picture pops up making it look like my character is walking, not quite sure how to do that though... Here's my code:
import java.awt.*;
public class Dude {
int x, dx, y;
Image still;
public Dude() {
ImageIcon i = new ImageIcon("Ken3.png");
ImageIcon ii = new ImageIcon("KenTurn1.png");
still = i.getImage();
x = 50;
y = 785;
}
public void move() {
x = x + dx;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return still;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A)
dx = -2;
if (key == KeyEvent.VK_D)
dx = 2;
if (key == KeyEvent.VK_SPACE)
dx = 5;
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A)
dx = 0;
if (key == KeyEvent.VK_D)
dx = 0;
Any help would be awesome thanks!
something like this, i commented it. Good luck
public class Dude {
private int walkingIndex;
private Image walkingFrames;
private Image still;
private String state;
public Dude() {
// say were starting off standing
state = "standing";
// init our still frame
still = (new ImageIcon("Ken3.png")).getImage();
// set our walking frame to 0 to start
walkingIndex = 0;
walkingFrames = new Image[3]; // or however many images you have in your walking animation
// go through each frame and initialize the image to KenWalking{index}.png
for(int i=0;i<walkingFrames.length;i++) {
walkingFrames[i] = (new ImageIcon("KenWalking"+i+".png")).getImage();
}
}
public void move() {
x+=dx;
// add 1 to the walking index and make sure its not greater than our number of walking frames, % means get the remainder of
// so 12 % 10 = 2, and 8 % 7 = 1
walkingIndex = (walkingIndex+1)%walkingFrames.length;
}
public Image getImage() {
// if our state is walking then give out a walking frame
if(state.equals("walking")) {
return walkingFrames[walkingIndex];
} else {
// otherwise we can assume were standing, so show that image instead
return still;
}
}
public void keyPressed(KeyEvent e) {
... same stuff
state = "walking";
}
public void keyReleased(KeyEvent e) {
... same stuff
state = "standing";
}
}
If i understand the question right, you are looking for a keyListener. In that case, you can do two things. Add keybindings or add an KeyListener.
Please have in mind that i haven't tested the code on your template, it work well for me in an AWT frame. Hope it helps
First implement the EventListener to Dude
public class Dude implements KeyListener{ ...
For the KeyListener to work you must have a focusable component..
component.addKeyListener(this);
component.setFocusable(true);
component.setFocusTraversalKeysEnabled(false);
The method below will be implemented with the KeyListener
#Override
public void keyPressed(KeyEvent e) {
int x = e.getKeyCode();
switch(x){
case KeyEvent.VK_UP:
// Do Your stuff
break;
case KeyEvent.VK_DOWN:
// Do Your stuff
break;
case KeyEvent.VK_RIGHT:
// Do Your stuff
break;
case KeyEvent.VK_LEFT:
// Do Your stuff
break;
}
}

Stop player movement when releasing a key

I am making a game in Java, and I am working on player movement, but whenever a press a directional key, the player moves but doesn't stop when I release the key.
I can't seem to see what I am doing wrong. May someone point me in the right direction?
// Input class implements KeyListener
public static final int LEFT = 0;
public static final int RIGHT = 1;
public static final int UP = 2;
public static final int DOWN = 3;
public boolean[] keys = new boolean[64];
public void getKeys(KeyEvent e, boolean move) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
keys[LEFT] = move;
break;
case KeyEvent.VK_RIGHT:
keys[RIGHT] = move;
break;
case KeyEvent.VK_UP:
keys[UP] = move;
break;
case KeyEvent.VK_DOWN:
keys[DOWN] = move;
break;
case KeyEvent.VK_BACK_QUOTE:
keys[BQUOTE] = move;
break;
}
keys[OTHER] = move;
}
#Override
public void keyPressed(KeyEvent e) {
getKeys(e, true);
}
#Override
public void keyReleased(KeyEvent e) {
getKeys(e, false);
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
// Player Class
public void tick() {
if (Engine.key_input.keys[KInput.LEFT]) {
dx = -speed;
animDir = SpriteLoader.L;
sprite = SpriteLoader.anim(SpriteLoader.ANIM_PLAYER, animDir);
}
if (Engine.key_input.keys[KInput.RIGHT]){
dx = speed;
animDir = SpriteLoader.R;
sprite = SpriteLoader.anim(SpriteLoader.ANIM_PLAYER, animDir);
}
if (Engine.key_input.keys[KInput.UP]){
dy = -speed;
animDir = SpriteLoader.U;
sprite = SpriteLoader.anim(SpriteLoader.ANIM_PLAYER, animDir);
}
if (Engine.key_input.keys[KInput.DOWN]){
dy = speed;
animDir = SpriteLoader.D;
sprite = SpriteLoader.anim(SpriteLoader.ANIM_PLAYER, animDir);
}
}
// Engine Class
public class Engine {
public Input key_input;
public Engine() {
key_input = new Input();
}
// add keyListener(Input) to component
}
This is not enough info from you. But this is suspicious:
public boolean[] keys = new boolean[64]
Where is the code that says, "I've used this keys value, now I want to ignore it next time"?
In your tick method, you only ever check for a "pressed" state, you never reset the movement delta
For example...
public void tick() {
if (Engine.key_input.keys[KInput.LEFT]) {
dx = -speed;
} else {
dx = 0;
}
I would make determinations of animDir and sprite based on the dx and dy variables after you've updated the deltas.
I would also check the left and right, and up and down in a single if block...
For example
if (Engine.key_input.keys[KInput.LEFT]) {
dx = -speed;
} else if (Engine.key_input.keys[KInput.RIGHT]) {
dx = speed;
} else{
dx = 0;
}
This ensures that you don't accidentally reset the movement
In your handler, you are only ever setting the keys[] = true, but you are not ever returning them back to false.
You need to add a keyReleased() method that will un-move all keys that have been released.

My boolean method java

I've done quite a bit of searching for an answer to this, and some editing and I cant get it to work. I think there's something wrong with my boolean method, getColor(). Im trying to use it in a loop from a different class.
herse my getColor method, from the AvatarPanel class
public boolean setColor(boolean good)
{
if (good == true)
what--;
avatars.get(0).setBackground(colors.get(what));
repaint();
if (good == false)
what++;
avatars.get(0).setBackground(colors.get(what));
repaint();
return good;
}
And here's the attackPerformed method from the Background class that Im trying to use getColor in. Im not sure if I wrote one of the methods wrong, or if attackPerformed needs a listener. The game is still running normally and working fine. I just wanted some help making sure these were at least written correctly.
I decided it might be a good idea to show the background constructor because I think its where I need to call attackPerformed. I can't figure out where it is that I need to call the attackPerformed, though I'm pretty sure it'll be in the background constructor. The attackPerformed method is shown below, constructor is at top.
public class Background extends JPanel implements Constants, ActionListener
{
private static final long serialVersionUID = 1L;
private final Color BACK_COLOR = Color.GRAY;
private ArrayList<Sprite> sprites;
private Avatar avatar;
/** Constructor */
public Background()
{
sprites = new ArrayList<Sprite>();
reset(0);
setBackground(BACK_COLOR);
KeyboardFocusManager manager =KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher(new KeyEventDispatcher()
{
public boolean dispatchKeyEvent(KeyEvent event)
{
int x = 0, y = 0;
double angle = 0;
Point p = avatar.getPosition();
switch (event.getKeyCode())
{
case KeyEvent.VK_DOWN:
y=6;
angle=270;
break;
case KeyEvent.VK_UP:
y = -6;
angle = 90;
break;
case KeyEvent.VK_LEFT:
x = -6;
break;
case KeyEvent.VK_RIGHT:
x = 6;
angle = 180;
break;
}
avatar.setParameters();
p.x += x;
p.y += y;
avatar.setPosition(p);
avatar.setAngle(angle);
if (!getBounds().contains(avatar.getBounds()))
{
avatar.restore();
Toolkit.getDefaultToolkit().beep();
return true;
}
repaint();
return true;
}
});
Timer timer = new Timer(15, this);
timer.start();
} //end of constructor
public void attackPerformed()
{
for(Sprite s : sprites)
{
AvatarPanel panel = new AvatarPanel();
Rectangle r = new Rectangle(sprites.get(0).getBounds());
Rectangle p = new Rectangle(sprites.get(1).getBounds());
if(r.intersects(p))
{
panel.setColor(false);
}
}
}
public void actionPerformed(ActionEvent e)
{
for (Sprite s : sprites)
{
if (s instanceof Move)
{
s.setParameters();
for (int i=0; i<3; i++)
{
((Move)s).nextPosition();
if (!getBounds().contains(s.getBounds()))
{
((Move) s).moveFailed();
}
else break;
}
}
}
repaint();
}
public #Override void paintComponent(Graphics g)
{
super.paintComponent(g); /* Let the parent class do its painting */
for (Sprite sprite: sprites)
{
sprite.draw(g);
}
}
public void reset(int level)
{
Sprite sprite = null;
int x, y, angle;
double scale, min, max;
sprites.clear();
int[] figures = FIGURES[level];
for (int f=0; f<figures.length; f++)
{
for (int i=0; i<figures[f]; i++)
{
x = (int)(Math.random()*600 + 100);
y = (int)(Math.random()*400 + 100);
switch (f)
{
case 0:
sprite = avatar = new Avatar(x,y);
break;
case 1:
sprite = new Predator(x,y);
break;
case 2:
sprite = new Mine(x,y);
break;
case 3:
sprite = new Shield(x,y);
break;
}
angle = (int)(Math.random()*360);
sprite.setAngle(angle);
min = sprite.getMinScaleFactor();
max = sprite.getMaxScaleFactor();
scale = Math.random() * (max - min) + min;
sprite.setScale(scale);
sprites.add(sprite);
repaint();
}
}
}
}
Looks like your if and else case are very similar.
You can simplify it to this.
public boolean setColor(boolean good)
{
what+=good?-1:+1;
avatars.get(0).setBackground(colors.get(what));
repaint();
    return good;
}
I would strongly recommend to use brackets, as the method repaint() would execute outside of if statement. Since, boolean can only have two possible values you can use 'else' instead of second if...
public boolean setColor(boolean good)
{
if (good == true)
{
what--;
avatars.get(0).setBackground(colors.get(what));
repaint();
}
else
{
what++;
avatars.get(0).setBackground(colors.get(what));
repaint();
}

Categories

Resources