I'm new to the site, as well as to Java. I'm playing around in BlueJ for one of my programming classes and we created a drawing and a sunset using slowMoveVertical, but I can't get my sun to "set" behind the horizon... you continue to see it set above it. Is there a way to change the layering so I can get it to "set" behind the horizon? Here's the whole code for the "Picture" class.
public class Picture
{
private Circle hill;
private Square wall;
private Square window;
private Triangle roof;
private Circle sun;
/**
* Constructor for objects of class Picture
*/
public Picture()
{
// nothing to do... instance variables are automatically set to null
}
/**
* Draw this picture.
*/
public void draw()
{
wall = new Square();
wall.moveVertical(80);
wall.changeSize(100);
wall.makeVisible();
window = new Square();
window.changeColor("black");
window.moveHorizontal(20);
window.moveVertical(100);
window.makeVisible();
roof = new Triangle();
roof.changeSize(50, 140);
roof.changeColor("blue");
roof.moveHorizontal(60);
roof.moveVertical(70);
roof.makeVisible();
sun = new Circle();
sun.changeColor("yellow");
sun.moveHorizontal(180);
sun.moveVertical(-10);
sun.changeSize(60);
sun.makeVisible();
hill = new Circle();
hill.changeColor("green");
hill.moveHorizontal(-360);
hill.moveVertical(160);
hill.changeSize(1000);
hill.makeVisible();
}
/**
* Change this picture to black/white display
*/
public void setBlackAndWhite()
{
if(wall != null) // only if it's painted already...
{
wall.changeColor("black");
window.changeColor("white");
roof.changeColor("black");
sun.changeColor("black");
hill.changeColor("black");
}
}
/**
* Change this picture to use color display
*/
public void setColor()
{
if(wall != null) // only if it's painted already...
{
wall.changeColor("red");
window.changeColor("black");
roof.changeColor("blue");
sun.changeColor("yellow");
hill.changeColor("green");
}
}
/**
* Change this picture to make the sun go down
*/
public void setSunset()
{
if(wall != null) // only if the sun is already up...
{
sun.slowMoveVertical(255);
}
And here is the code for class "Circle".
public class Circle
{
private int diameter;
private int xPosition;
private int yPosition;
private String color;
private boolean isVisible;
/**
* Create a new circle at default position with default color.
*/
public Circle()
{
diameter = 30;
xPosition = 20;
yPosition = 60;
color = "blue";
isVisible = false;
}
/**
* Make this circle visible. If it was already visible, do nothing.
*/
public void makeVisible()
{
isVisible = true;
draw();
}
/**
* Make this circle invisible. If it was already invisible, do nothing.
*/
public void makeInvisible()
{
erase();
isVisible = false;
}
/**
* Move the circle a few pixels to the right.
*/
public void moveRight()
{
moveHorizontal(20);
}
/**
* Move the circle a few pixels to the left.
*/
public void moveLeft()
{
moveHorizontal(-20);
}
/**
* Move the circle a few pixels up.
*/
public void moveUp()
{
moveVertical(-20);
}
/**
* Move the circle a few pixels down.
*/
public void moveDown()
{
moveVertical(20);
}
/**
* Move the circle horizontally by 'distance' pixels.
*/
public void moveHorizontal(int distance)
{
erase();
xPosition += distance;
draw();
}
/**
* Move the circle vertically by 'distance' pixels.
*/
public void moveVertical(int distance)
{
erase();
yPosition += distance;
draw();
}
/**
* Slowly move the circle horizontally by 'distance' pixels.
*/
public void slowMoveHorizontal(int distance)
{
int delta;
if(distance < 0)
{
delta = -1;
distance = -distance;
}
else
{
delta = 1;
}
for(int i = 0; i < distance; i++)
{
xPosition += delta;
draw();
}
}
/**
* Slowly move the circle vertically by 'distance' pixels.
*/
public void slowMoveVertical(int distance)
{
int delta;
if(distance < 0)
{
delta = -1;
distance = -distance;
}
else
{
delta = 1;
}
for(int i = 0; i < distance; i++)
{
yPosition += delta;
draw();
}
}
/**
* Change the size to the new size (in pixels). Size must be >= 0.
*/
public void changeSize(int newDiameter)
{
erase();
diameter = newDiameter;
draw();
}
/**
* Change the color. Valid colors are "red", "yellow", "blue", "green",
* "magenta" and "black".
*/
public void changeColor(String newColor)
{
color = newColor;
draw();
}
/*
* Draw the circle with current specifications on screen.
*/
private void draw()
{
if(isVisible) {
Canvas canvas = Canvas.getCanvas();
canvas.draw(this, color, new Ellipse2D.Double(xPosition, yPosition,
diameter, diameter));
canvas.wait(10);
}
}
/*
* Erase the circle on screen.
*/
private void erase()
{
if(isVisible) {
Canvas canvas = Canvas.getCanvas();
canvas.erase(this);
}
}
The loop in slowMoveVertical pretty much locks you into drawing the sun in front. If your assignment allows you to bypass slowMoveVertical, then you can manually do the loop it does and render your sun and the hill yourself so the layering is right.
for(int i = 0; i < 190; i++) {
sun.moveHorizontal(1);
hill.draw();
}
edit...
There's a wait() at the end of the draw call, which would really only be used on the last object in the "batch". Making another draw method with an optional wait call allows the caller to control it instead of the circle. example...
public void draw() {
draw(true); // retain current behavior
{
public void draw(boolean useWait) {
if(isVisible) {
Canvas canvas = Canvas.getCanvas();
canvas.draw(this, color, new Ellipse2D.Double(xPosition, yPosition,
diameter, diameter));
if (useWait) {
canvas.wait(10);
}
}
}
Now you can call sun.draw(false) and hill.draw(true) and it shouldn't flicker (or a at least a lot less).
Related
Here's my touchpad.
What I want is this: when I touch background of touchpad (not knob), knob move to this position. Code, which I use for touchpad from github/libgdx/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Touchpad.java
package com.liketurbo.funnyGame;
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
import com.badlogic.gdx.scenes.scene2d.Event;
import com.badlogic.gdx.scenes.scene2d.EventListener;
import com.badlogic.gdx.scenes.scene2d.ui.Widget;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.Circle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.Pools;
/** An on-screen joystick. The movement area of the joystick is circular, centered on the touchpad, and its size determined by the
* smaller touchpad dimension.
* <p>
* The preferred size of the touchpad is determined by the background.
* <p>
* {#link ChangeEvent} is fired when the touchpad knob is moved. Cancelling the event will move the knob to where it was
* previously.
* #author Josh Street */
public class Touchpad extends Widget {
private TouchpadStyle style;
boolean touched;
boolean resetOnTouchUp = true;
private float deadzoneRadius;
private final Circle knobBounds = new Circle(0, 0, 0);
private final Circle touchBounds = new Circle(0, 0, 0);
private final Circle deadzoneBounds = new Circle(0, 0, 0);
private final Vector2 knobPosition = new Vector2();
private final Vector2 knobPercent = new Vector2();
/** #param deadzoneRadius The distance in pixels from the center of the touchpad required for the knob to be moved. */
public Touchpad (float deadzoneRadius, Skin skin) {
this(deadzoneRadius, skin.get(TouchpadStyle.class));
}
/** #param deadzoneRadius The distance in pixels from the center of the touchpad required for the knob to be moved. */
public Touchpad (float deadzoneRadius, Skin skin, String styleName) {
this(deadzoneRadius, skin.get(styleName, TouchpadStyle.class));
}
/** #param deadzoneRadius The distance in pixels from the center of the touchpad required for the knob to be moved. */
public Touchpad (float deadzoneRadius, TouchpadStyle style) {
if (deadzoneRadius < 0) throw new IllegalArgumentException("deadzoneRadius must be > 0");
this.deadzoneRadius = deadzoneRadius;
knobPosition.set(getWidth() / 2f, getHeight() / 2f);
setStyle(style);
setSize(getPrefWidth(), getPrefHeight());
addListener(new InputListener() {
#Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
if (touched) return false;
touched = true;
calculatePositionAndValue(x, y, false);
return true;
}
#Override
public void touchDragged (InputEvent event, float x, float y, int pointer) {
calculatePositionAndValue(x, y, false);
}
#Override
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
touched = false;
calculatePositionAndValue(x, y, resetOnTouchUp);
}
});
}
void calculatePositionAndValue (float x, float y, boolean isTouchUp) {
float oldPositionX = knobPosition.x;
float oldPositionY = knobPosition.y;
float oldPercentX = knobPercent.x;
float oldPercentY = knobPercent.y;
float centerX = knobBounds.x;
float centerY = knobBounds.y;
y = centerY;
knobPosition.set(centerX, centerY);
knobPercent.set(0f, 0f);
if (!isTouchUp) {
if (!deadzoneBounds.contains(x, y)) {
knobPercent.set((x - centerX) / knobBounds.radius*3.5f, 0);
float length = knobPercent.len();
if (length > 1) knobPercent.scl(1 / length);
if (knobBounds.contains(x, y)) {
knobPosition.set(x, y);
} else {
knobPosition.set(knobPercent).nor().scl(knobBounds.radius*3.5f).add(knobBounds.x, knobBounds.y);
}
}
}
if (oldPercentX != knobPercent.x || oldPercentY != knobPercent.y) {
ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class);
if (fire(changeEvent)) {
knobPercent.set(oldPercentX, oldPercentY);
knobPosition.set(oldPositionX, oldPositionY);
}
Pools.free(changeEvent);
}
}
public void setStyle (TouchpadStyle style) {
if (style == null) throw new IllegalArgumentException("style cannot be null");
this.style = style;
invalidateHierarchy();
}
/** Returns the touchpad's style. Modifying the returned style may not have an effect until {#link #setStyle(TouchpadStyle)} is
* called. */
public TouchpadStyle getStyle () {
return style;
}
#Override
public Actor hit (float x, float y, boolean touchable) {
return touchBounds.contains(x, y) ? this : null;
}
#Override
public void layout () {
// Recalc pad and deadzone bounds
float halfWidth = getWidth() / 2;
float halfHeight = getHeight() / 2;
float radius = Math.min(halfWidth, halfHeight);
touchBounds.set(halfWidth, halfHeight, radius);
if (style.knob != null) radius -= Math.max(style.knob.getMinWidth(), style.knob.getMinHeight()) / 2;
knobBounds.set(halfWidth, halfHeight, radius);
deadzoneBounds.set(halfWidth, halfHeight, deadzoneRadius);
// Recalc pad values and knob position
knobPosition.set(halfWidth, halfHeight);
knobPercent.set(0, 0);
}
#Override
public void draw (Batch batch, float parentAlpha) {
validate();
Color c = getColor();
batch.setColor(c.r, c.g, c.b, c.a * parentAlpha);
float x = getX();
float y = getY();
float w = getWidth();
float h = getHeight();
final Drawable bg = style.background;
if (bg != null) bg.draw(batch, x, y, w, h);
final Drawable knob = style.knob;
if (knob != null) {
x += knobPosition.x - (knob.getMinWidth()*2) / 2f;
y += knobPosition.y - (knob.getMinHeight()*2) / 2f;
knob.draw(batch, x, y, knob.getMinWidth()*2, knob.getMinHeight()*2);
}
}
#Override
public float getPrefWidth () {
return style.background != null ? style.background.getMinWidth() : 0;
}
#Override
public float getPrefHeight () {
return style.background != null ? style.background.getMinHeight() : 0;
}
public boolean isTouched () {
return touched;
}
public boolean getResetOnTouchUp () {
return resetOnTouchUp;
}
/** #param reset Whether to reset the knob to the center on touch up. */
public void setResetOnTouchUp (boolean reset) {
this.resetOnTouchUp = reset;
}
/** #param deadzoneRadius The distance in pixels from the center of the touchpad required for the knob to be moved. */
public void setDeadzone (float deadzoneRadius) {
if (deadzoneRadius < 0) throw new IllegalArgumentException("deadzoneRadius must be > 0");
this.deadzoneRadius = deadzoneRadius;
invalidate();
}
/** Returns the x-position of the knob relative to the center of the widget. The positive direction is right. */
public float getKnobX () {
return knobPosition.x;
}
/** Returns the y-position of the knob relative to the center of the widget. The positive direction is up. */
public float getKnobY () {
return knobPosition.y;
}
/** Returns the x-position of the knob as a percentage from the center of the touchpad to the edge of the circular movement
* area. The positive direction is right. */
public float getKnobPercentX () {
return knobPercent.x;
}
/** Returns the y-position of the knob as a percentage from the center of the touchpad to the edge of the circular movement
* area. The positive direction is up. */
public float getKnobPercentY () {
return knobPercent.y;
}
/** The style for a {#link Touchpad}.
* #author Josh Street */
public static class TouchpadStyle {
/** Stretched in both directions. Optional. */
public Drawable background;
/** Optional. */
public Drawable knob;
public TouchpadStyle () {
}
public TouchpadStyle (Drawable background, Drawable knob) {
this.background = background;
this.knob = knob;
}
public TouchpadStyle (TouchpadStyle style) {
this.background = style.background;
this.knob = style.knob;
}
}
}
Line addListener(new InputListener() {...} works only for knob, if I can figure out how make it work for touchpad's background too, it solved my problem. Does somebody know how solve this problem? Thank you in advance.
You shouldn't add listener to your touchpad. Just limit touch area of the screen where touchpad can be used.
Here is code to activate only on right half of a screen:
private Touchpad touchpad;
private Vector2 screenPos = new Vector2(); // position where touch occurs
private Vector2 localPos = new Vector2(); // position in local coordinates
private InputEvent fakeTouchDownEvent = new InputEvent(); // fake touch for correct work
private Vector2 stagePos; // position to fire touch event
private void getDirection() {
if (Gdx.input.justTouched()) {
// Get the touch point in screen coordinates.
screenPos.set(Gdx.input.getX(), Gdx.input.getY());
if (screenPos.x > Gdx.graphics.getWidth() / 2) { // right half of a screen
// Convert the touch point into local coordinates, place the touchpad and show it.
localPos.set(screenPos);
localPos = touchpad.getParent().screenToLocalCoordinates(localPos);
touchpad.setPosition(localPos.x - touchpad.getWidth() / 2, localPos.y - touchpad.getHeight() / 2);
// Fire a touch down event to get the touchpad working.
Vector2 stagePos = touchpad.getStage().screenToStageCoordinates(screenPos);
fakeTouchDownEvent.setStageX(stagePos.x);
fakeTouchDownEvent.setStageY(stagePos.y);
touchpad.fire(fakeTouchDownEvent);
}
}
}
I am trying to make an Asteroids game clone in JavaFX. So far, I have been able to draw the ship and asteroids onto the screen (where Rectangles represent them, for now). I have also implemented movement for the ship, and randomized movements for the asteroids.
I am having trouble implementing the code needed to bounce the asteroids off each other. The current method that does the collision checking (called checkAsteroidCollisions) is bugged in that all asteroids start stuttering in place. They don't move, but rather oscillate back and forth in place rapidly. Without the call to this method, all asteroids begin moving normally and as expected.
Instead, I want each asteroid to move freely and, when coming into contact with another asteroid, bounce off each other like in the actual Asteroids game.
MainApp.java
import java.util.ArrayList;
import java.util.HashSet;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class MainApp extends Application {
private static final int WIDTH = 700;
private static final int HEIGHT = 900;
private static final int NUM_OF_ASTEROIDS = 12;
private static final Color ASTEROID_COLOR = Color.GRAY;
private static final Color PLAYER_COLOR = Color.BLUE;
private Player player;
private ArrayList<Entity> asteroids;
long lastNanoTime; // For AnimationTimer
HashSet<String> inputs; // For inputs
private static final int MAX_SPEED = 150;
private static final int SPEED = 10;
private static final int ASTEROID_SPEED = 150;
private StackPane background;
/*
* Generates a random number between min and max, inclusive.
*/
private float genRandom(int min, int max) {
return (float) Math.floor(Math.random() * (max - min + 1) + min);
}
/*
* Initializes the asteroids
*/
private void initAsteroids() {
this.asteroids = new ArrayList<Entity>();
for (int i = 0; i < NUM_OF_ASTEROIDS; i++) {
Entity asteroid = new Entity(50, 50, ASTEROID_COLOR, EntityType.ASTEROID);
float px = (float) genRandom(200, WIDTH - 50);
float py = (float) genRandom(200, HEIGHT - 50);
asteroid.setPos(px, py);
// Keep recalculating position until there are no collisions
while (asteroid.intersectsWith(this.asteroids)) {
px = (float) genRandom(200, WIDTH - 50);
py = (float) genRandom(200, HEIGHT - 50);
asteroid.setPos(px, py);
}
// Randomly generate numbers to change velocity by
float dx = this.genRandom(-ASTEROID_SPEED, ASTEROID_SPEED);
float dy = this.genRandom(-ASTEROID_SPEED, ASTEROID_SPEED);
asteroid.changeVelocity(dx, dy);
this.asteroids.add(asteroid);
}
}
/*
* Initializes the player
*/
private void initPlayer() {
this.player = new Player(30, 30, PLAYER_COLOR, EntityType.PLAYER);
this.player.setPos(WIDTH / 2, 50);
}
/*
* Checks collisions with screen boundaries
*/
private void checkOffScreenCollisions(Entity e) {
if (e.getX() < -50)
e.setX(WIDTH);
if (e.getX() > WIDTH)
e.setX(0);
if (e.getY() < -50)
e.setY(HEIGHT);
if (e.getY() > HEIGHT)
e.setY(0);
}
/*
* Controls speed
*/
private void controlSpeed(Entity e) {
if (e.getDx() < -MAX_SPEED)
e.setDx(-MAX_SPEED);
if (e.getDx() > MAX_SPEED)
e.setDx(MAX_SPEED);
if (e.getDy() < -MAX_SPEED)
e.setDy(-MAX_SPEED);
if (e.getDy() > MAX_SPEED)
e.setDy(MAX_SPEED);
}
/*
* Controls each asteroid's speed and collision off screen
*/
private void controlAsteroids(ArrayList<Entity> asteroids) {
for (Entity asteroid : asteroids) {
this.checkOffScreenCollisions(asteroid);
this.controlSpeed(asteroid);
}
}
/*
* Checks an asteroid's collision with another asteroid
*/
private void checkAsteroidCollisions() {
for (int i = 0; i < NUM_OF_ASTEROIDS; i++) {
Entity asteroid = this.asteroids.get(i);
if (asteroid.intersectsWith(this.asteroids)){
float dx = (float) asteroid.getDx();
float dy = (float) asteroid.getDy();
asteroid.setDx(0);
asteroid.setDy(0);
asteroid.changeVelocity(-dx, -dy);
}
}
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Hello World!");
this.initAsteroids();
this.initPlayer();
background = new StackPane();
background.setStyle("-fx-background-color: pink");
this.inputs = new HashSet<String>();
Group root = new Group();
Scene scene = new Scene(root);
primaryStage.setScene(scene);
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent e) {
String code = e.getCode().toString();
inputs.add(code);
}
});
scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent e) {
String code = e.getCode().toString();
inputs.remove(code);
}
});
Canvas canvas = new Canvas(WIDTH, HEIGHT);
GraphicsContext gc = canvas.getGraphicsContext2D();
background.getChildren().add(canvas);
root.getChildren().add(background);
lastNanoTime = System.nanoTime();
new AnimationTimer() {
#Override
public void handle(long currentNanoTime) {
float elapsedTime = (float) ((currentNanoTime - lastNanoTime) / 1000000000.0);
lastNanoTime = currentNanoTime;
/* PLAYER */
// Game Logic
if (inputs.contains("A"))
player.changeVelocity(-SPEED, 0);
if (inputs.contains("D"))
player.changeVelocity(SPEED, 0);
if (inputs.contains("W"))
player.changeVelocity(0, -SPEED);
if (inputs.contains("S"))
player.changeVelocity(0, SPEED);
// Collision with edge of map
checkOffScreenCollisions(player);
// Control speed
controlSpeed(player);
player.update(elapsedTime);
/* ASTEROIDS */
gc.setFill(ASTEROID_COLOR);
for(int i = 0; i < NUM_OF_ASTEROIDS; i++) {
checkAsteroidCollisions(i); // BUGGY CODE
}
controlAsteroids(asteroids);
gc.clearRect(0, 0, WIDTH, HEIGHT);
for (Entity asteroid : asteroids) {
asteroid.update(elapsedTime);
asteroid.render(gc);
}
gc.setFill(PLAYER_COLOR);
player.render(gc);
}
}.start();
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Entity.java:
import java.util.ArrayList;
import javafx.geometry.Rectangle2D;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
public class Entity {
private Color color;
private double x, y, width, height, dx, dy;
private EntityType entityType; // ID of this Entity
public Entity(float width, float height, Color color, EntityType type) {
this.x = this.dx = 0;
this.y = this.dy = 0;
this.width = width;
this.height = height;
this.color = color;
this.entityType = type;
}
/*
* Getters and setters
*/
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public double getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public double getDx() {
return dx;
}
public void setDx(float dx) {
this.dx = dx;
}
public double getDy() {
return dy;
}
public void setDy(float dy) {
this.dy = dy;
}
public EntityType getEntityType() {
return entityType;
}
/*
* Adds to dx and dy (velocity)
*/
public void changeVelocity(float dx, float dy) {
this.dx += dx;
this.dy += dy;
}
/*
* Sets position
*/
public void setPos(float x, float y) {
this.setX(x);
this.setY(y);
}
/*
* Gets new position of the Entity based on velocity and time
*/
public void update(float time) {
this.x += this.dx * time;
this.y += this.dy * time;
}
/*
* Used for collisions
*/
public Rectangle2D getBoundary() {
return new Rectangle2D(this.x, this.y, this.width, this.height);
}
/*
* Checks for intersections
*/
public boolean intersectsWith(Entity e) {
return e.getBoundary().intersects(this.getBoundary());
}
/*
* If any of the entities in the passed in ArrayList
* intersects with this, then return true;
*/
public boolean intersectsWith(ArrayList<Entity> entities) {
for(Entity e : entities) {
if(e.getBoundary().intersects(this.getBoundary()))
return true;
}
return false;
}
/*
* Draws the shape
*/
public void render(GraphicsContext gc) {
gc.fillRoundRect(x, y, width, height, 10, 10);
}
#Override
public String toString() {
return "Entity [x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + ", entityType=" + entityType
+ "]";
}
}
I think you will need to change the position of the two colliding asteroids slightly so their state is not on collision anymore.
What happens right now is that you change their movement after the collision but I guess that your algorithm notices that they are still touching, so it will try to change the movement again with the same result as before.
What you need to implement now is a change in the position of the two asteroids so your collision detection won´t act up again immediately after it´s first call.
I hope I could help you.
I'm a beginner android game programmer, I use LIBgdx
I have a playState class
public PlayState(GameStateManager gsm) {
super(gsm);
obj = new Objects();
cam.setToOrtho(false, Game.WIDTH , Game.HEIGHT);
}
#Override
public void update(float dt) {
obj.update(dt);
}
I have an Objects class
public class Objects {
private Vector2 posObj;
private static final int MOVEMENT = 2;
private Vector2 velo;
private Texture objTx;
private Random rand;
private static final int FLUCTUATION = 400;
public Objects(){
objTX = new Texture("objies.png");
rand = new Random();
posObj = new Vector2(rand.nextInt(FLUCTUATION),rand.nextInt(FLUCTUATION));
velo = new Vector2(0, 0);
}
public void update(float dt){
}
Now, What I'm tring to do is:
Move this randomly generated object to the center of the screen and then dispose.
Serious Help required! Thank-you
Well, you know where your object is and you know where the middle is (Game.WIDTH/2 , Game.HEIGHT/2)
If the center is to the left of the object move it to the left, if center is above move object up etc.
So a very simple solution:
public void update(float delta){
if(posObj.x < Game.WIDTH/2){
velocity.x = MOVEMENT;
}
else {
velocity.x = -MOVEMENT;
}
if(posObj.y < Game.HEIGHT/2){
velocity.y = MOVEMENT;
}
else {
velocity.y = -MOVEMENT;
}
posObj.y += velocity.y * delta;
posObj.x += velocity.x * delta;
}
This might cause your object to jump around the middle without ever really hitting the exact coordinates. So you can check the distance from the object to the middle by adding this method to your object:
public Vector2d getPosition(){
return posObj;
}
And then check for the distance:
if( obj.dst(Game.WIDTH , Game.HEIGHT) <= closeEnough ){
obj = new Objects();
}
closeEnough is a distance you set.
How can I quickly and efficiently set all pixels of a BufferedImage to transparent so that I can simply redraw what sprite graphics I want for each frame?
I am designing a simple game engine in java that updates a background and foreground BufferedImage and draws them to a composite VolatileImage for efficient scaling, to be drawn to a JPanel. This scalable model allows me to add more layers and iterate over each drawing layer.
I simplified my application into one class given below that demonstrates my issue. Use the arrow keys to move a red square over the image. The challenge is I want to decouple updating the game graphics from drawing the composite graphics to the game engine. I have studied seemingly thorough answers to this question but cannot figure out how to apply them to my application:
Java: Filling a BufferedImage with transparent pixels
Here is the critical section that does not clear the pixels correctly. The commented out section is from stack-overflow answers I have read already, but they either draw the background as a non-transparent black or white. I know the foregroundImage begins with transparent pixels in my implementation as you can see the random pixel noise of the backgroundImage behind the red sprite when the application begins. Right now, the image is not cleared, so the previous drawn images remain.
/** Update the foregroundGraphics. */
private void updateGraphics(){
Graphics2D fgGraphics = (Graphics2D) foregroundImage.getGraphics();
// set image pixels to transparent
//fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
//fgGraphics.setColor(new Color(0,0,0,0));
//fgGraphics.clearRect(0, 0, width, height);
//fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// draw again.
fgGraphics.setColor(Color.RED);
fgGraphics.fillRect(sx, sy, spriteSize, spriteSize);
fgGraphics.dispose();
}
Here is my entire example code:
/**
* The goal is to draw two BufferedImages quickly onto a scalable JPanel, using
* a VolatileImage as a composite.
*/
public class Example extends JPanel implements Runnable, KeyListener
{
private static final long serialVersionUID = 1L;
private int width;
private int height;
private Object imageLock;
private Random random;
private JFrame frame;
private Container contentPane;
private BufferedImage backgroundImage;
private BufferedImage foregroundImage;
private VolatileImage compositeImage;
private Graphics2D compositeGraphics;
private int[] backgroundPixels;
private int[] foregroundPixels;
// throttle the framerate.
private long prevUpdate;
private int frameRate;
private int maximumWait;
// movement values.
private int speed;
private int sx;
private int sy;
private int dx;
private int dy;
private int spriteSize;
/** Setup required fields. */
public Example(){
width = 512;
height = 288;
super.setPreferredSize(new Dimension(width, height));
imageLock = new Object();
random = new Random();
frame = new JFrame("BufferedImage Example");
frame.addKeyListener(this);
contentPane = frame.getContentPane();
contentPane.add(this, BorderLayout.CENTER);
// used to create hardware-accelerated images.
GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
backgroundImage = gc.createCompatibleImage(width, height,Transparency.TRANSLUCENT);
foregroundImage = gc.createCompatibleImage(width, height,Transparency.TRANSLUCENT);
compositeImage = gc.createCompatibleVolatileImage(width, height,Transparency.TRANSLUCENT);
compositeGraphics = compositeImage.createGraphics();
compositeGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
compositeGraphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
backgroundPixels = ((DataBufferInt) backgroundImage.getRaster().getDataBuffer()).getData();
foregroundPixels = ((DataBufferInt) foregroundImage.getRaster().getDataBuffer()).getData();
//initialize the background image.
for(int i = 0; i < backgroundPixels.length; i++){
backgroundPixels[i] = random.nextInt();
}
// used to throttle frames per second
frameRate = 180;
maximumWait = 1000 / frameRate;
prevUpdate = System.currentTimeMillis();
// used to update sprite state.
speed = 1;
dx = 0;
dy = 0;
sx = 0;
sy = 0;
spriteSize = 32;
}
/** Renders the compositeImage to the Example, scaling to fit. */
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// draw the composite, scaled to the JPanel.
synchronized (imageLock) {
((Graphics2D) g).drawImage(compositeImage, 0, 0, super.getWidth(), super.getHeight(), 0, 0, width, height, null);
}
// force repaint.
repaint();
}
/** Update the BufferedImage states. */
#Override
public void run() {
while(true){
updateSprite();
updateGraphics();
updateComposite();
throttleUpdateSpeed();
}
}
/** Update the Sprite's position. */
private void updateSprite(){
// update the sprite state from the inputs.
dx = 0;
dy = 0;
if (Command.UP.isPressed()) dy -= speed;
if (Command.DOWN.isPressed()) dy += speed;
if (Command.LEFT.isPressed()) dx -= speed;
if (Command.RIGHT.isPressed()) dx += speed;
sx += dx;
sy += dy;
// adjust to keep in bounds.
sx = sx < 0 ? 0 : sx + spriteSize >= width ? width - spriteSize : sx;
sy = sy < 0 ? 0 : sy + spriteSize >= height ? height - spriteSize : sy;
}
/** Update the foregroundGraphics. */
private void updateGraphics(){
Graphics2D fgGraphics = (Graphics2D) foregroundImage.getGraphics();
// set image pixels to transparent
//fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
//fgGraphics.setColor(new Color(255, 255, 255, 255));
//fgGraphics.clearRect(0, 0, width, height);
//fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// draw again.
fgGraphics.setColor(Color.RED);
fgGraphics.fillRect(sx, sy, spriteSize, spriteSize);
fgGraphics.dispose();
}
/** Draw the background and foreground images to the volatile composite. */
private void updateComposite(){
synchronized (imageLock) {
compositeGraphics.drawImage(backgroundImage, 0, 0, null);
compositeGraphics.drawImage(foregroundImage, 0, 0, null);
}
}
/** Keep the update rate around 60 FPS. */
public void throttleUpdateSpeed(){
try {
Thread.sleep(Math.max(0, maximumWait - (System.currentTimeMillis() - prevUpdate)));
prevUpdate = System.currentTimeMillis();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
/** Ignore key typed events. */
#Override
public void keyTyped(KeyEvent e) {}
/** Handle key presses. */
#Override
public void keyPressed(KeyEvent e) {
setCommandPressedFrom(e.getKeyCode(), true);
}
/** Handle key releases. */
#Override
public void keyReleased(KeyEvent e) {
setCommandPressedFrom(e.getKeyCode(), false);
}
/** Switch over key codes and set the associated Command's pressed value. */
private void setCommandPressedFrom(int keycode, boolean pressed){
switch (keycode) {
case KeyEvent.VK_UP:
Command.UP.setPressed(pressed);
break;
case KeyEvent.VK_DOWN:
Command.DOWN.setPressed(pressed);
break;
case KeyEvent.VK_LEFT:
Command.LEFT.setPressed(pressed);
break;
case KeyEvent.VK_RIGHT:
Command.RIGHT.setPressed(pressed);
break;
}
}
/** Commands are used to interface with key press values. */
public enum Command{
UP, DOWN, LEFT, RIGHT;
private boolean pressed;
/** Press the Command. */
public void press() {
if (!pressed) pressed = true;
}
/** Release the Command. */
public void release() {
if (pressed) pressed = false;
}
/** Check if the Command is pressed. */
public boolean isPressed() {
return pressed;
}
/** Set if the Command is pressed. */
public void setPressed(boolean pressed) {
if (pressed) press();
else release();
}
}
/** Begin the Example. */
public void start(){
try {
// create and display the frame.
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
Example e = new Example();
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
// start updating from key inputs.
Thread t = new Thread(this);
t.start();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
/** Start the application. */
public static void main(String[] args){
Example e = new Example();
e.start();
}
}
Edits:
- Fixed a typo in the for-loop initializing the backgroundPixels to random.
Turns out I goofed in my method selection. I noticed I was clearing a one-pixel wide box that was the outline of my graphics. This is because I accidentally used drawRect() instead of fillRect(). Upon changing my code it works now. Here are examples I was able to get to work.
Example using AlphaComposite.CLEAR (draw with any opaque color):
// clear pixels
fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR));
fgGraphics.setColor(new Color(255,255,255,255));
fgGraphics.fillRect(0, 0, width, height);
fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// draw new graphics
Example using AlphaComposite.SRC_OUT (draw with any color with alpha zero):
// clear pixels
fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OUT));
fgGraphics.setColor(new Color(255,255,255,0));
fgGraphics.fillRect(0, 0, width, height);
fgGraphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
// draw new graphics
In the past few days I've been porting my game (Apopalypse) to the Android Mobile platform. I've did a quick search on Google of sprite touch detection but didn't find anything helpful. Each balloon will pop once touched and I just need to detect if it's touched.
Here's my balloon spawning code:
Rendering (x, y, width, and height are randomized):
public void render() {
y += 2;
balloon.setX(x);
balloon.setY(y);
balloon.setSize(width, height);
batch.begin();
balloon.draw(batch);
batch.end();
}
Spawning in main game class:
addBalloon(new Balloon());
public static void addBalloon(Balloon b) {
balloons.add(b);
}
in your class having the render method use can do following code:
Vector3 touchPoint=new Vector3();
void update()
{
if(Gdx.input.justTouched())
{
//unprojects the camera
camera.unproject(touchPoint.set(Gdx.input.getX(),Gdx.input.getY(),0));
if(balloon.getBoundingRectangles().contains(touchPoint.x,touchPoint.y))
{
// will be here when balloon will be touched
}
}
}
This is how I did it, but depending on the scene you are using and the elements that can be touched, there can be slightly more optimized ways of doing this:
public GameScreen implements Screen, InputProcessor
{
#Override
public void show()
{
Gdx.input.setInputProcessor(this);
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button)
{
float pointerX = InputTransform.getCursorToModelX(windowWidth, screenX);
float pointerY = InputTransform.getCursorToModelY(windowHeight, screenY);
for(int i = 0; i < balloons.size(); i++)
{
if(balloons.get(i).contains(pointerX, pointerY))
{
balloons.get(i).setSelected(true);
}
}
return true;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button)
{
float pointerX = InputTransform.getCursorToModelX(windowWidth, screenX);
float pointerY = InputTransform.getCursorToModelY(windowHeight, screenY);
for(int i = 0; i < balloons.size(); i++)
{
if(balloons.get(i).contains(pointerX, pointerY) && balloons.get(i).getSelected())
{
balloons.get(i).execute();
}
balloons.get(i).setSelected(false);
}
return true;
}
public class InputTransform
{
private static int appWidth = 480;
private static int appHeight = 320;
public static float getCursorToModelX(int screenX, int cursorX)
{
return (((float)cursorX) * appWidth) / ((float)screenX);
}
public static float getCursorToModelY(int screenY, int cursorY)
{
return ((float)(screenY - cursorY)) * appHeight / ((float)screenY) ;
}
}
i made a little class that i use for my games to detect is Sprite is touched
public class SpriteTouchable extends Sprite {
public SpriteTouchable(Texture texture) {
super(texture);
}
public SpriteTouchable(Sprite sprite) {
set(sprite);
}
public static float xTrans(float x)
{
return x*Gdx.graphics.getWidth()/480;
}
public static float yTrans(float y)
{
return y*Gdx.graphics.getHeight()/320;
}
private boolean isTouched;
/**
* Type: Input Listener function
* listen if this sprite button was pressed (touched)
* #param marge : the extra touchable space out of sprite
* #param x : x position touched by user
* #param y : y position touched by user
*
* return true : Sprite touched
* return false : Sprite not touched
*/
public boolean isPressing(int marge,int x, int y) {
if((x>getX() -xTrans(marge))&& x<getX() +getWidth()+xTrans(marge)) {
if((y>getY() -yTrans(marge))&& y<getY()+getHeight()+yTrans(marge)) {
return true;
}
}
return false;
}
}
public boolean isTouched() {
return isTouched;
}
here how i use it
Gdx.input.setInputProcessor(new GameInputListener() {
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchDown(int x, int yy, int pointer, int button) {
int y = Gdx.graphics.getHeight() - yy;
// if sprite + 10 of px marge is touched
if(mySpriteTouchable.isPressing(10, x, y)) {
// sprite is touched down
}
return false;
}
}
with the same logic you can detect sprite releasing and also you can customize it for effect size when the sprite is touched and more...
hope this was helpfull !
You have Gdx.input.getX() and Gdx.input.getY(). The X and Y coordinates of the last touch.
Just compare them with balloon frame.
You could add a tiny 1x1 pixel rectangle to your mouse and check if it intersects or contains other boxes. You do need to use boxes for all your objects you want to make clickable this way.
i have a simple solution
it's like that create a small rectangle 1 pixel by one pixel
Rectangle rect;
rect = new Rectangle(0, 0, 1, 1);
then make a method called
touching_checking();
in this method we will do three things
first check if screen is touched
second put the rectangle where you touch the screen
then at last check if your rectangle overlaps with the sprite rectangle.
like that
private void touching_checking() {
if (Gdx.input.isTouched()) {
rect.setPosition(Gdx.input.getX(), Gdx.input.getY());
if (rect.overlaps(back.getBoundingRectangle())) {
//do what you want here
}
}
}
i have an array of sprites called levels i check which one i pressed like that
private void touching_checking() {
if (Gdx.input.isTouched()) {
rect.setPosition(Gdx.input.getX(), Gdx.graphics.getWidth() - Gdx.input.getY());
for (int i = 0; i < levels.size; i++) {
if (rect.overlaps(levels.get(i).getBoundingRectangle())) {
//do what you want here
}
}
}
}
Here is what i use in my sprite class. I give it the vector where i clicked camera.unproject(new Vector3().set(x,y,0));. returns true if clicked in the area of the sprite.
/***
*
* #param v3 Vector with MouseClickPosition
* #return true if click was inside rectangle x --> x + width, y --> y +
* height
*/
public boolean clicked(Vector3 v3){
Rectangle rec = getBoundingRectangle();
if(v3.x >= rec.x && v3.x < rec.x + getWidth()){
if(v3.y >= rec.y && v3.y < rec.y + getHeight()){
System.out.println("click_on\t" + v3.x + ", " + v3.y);
return true;
}
else{
return false;
}
}
else{
return false;
}
}