I've created objects already in the canvas method. But I need help on how to create an arraylist and to add these four objects to the arraylist so that they will constantly appear. I've looked at the arraylist Heres the code, any assistance will be greatly appreciated.
public class BouncingBallView extends View {
private int xMin = 0; // This view's bounds
private int xMax;
private int yMin = 0;
private int yMax;
private int xMin1 = 0; // This view's bounds
private int xMax1;
private int yMin1 = 0;
private int yMax1;
private int xMin2 = 0; // This view's bounds
private int xMax2;
private int yMin2 = 0;
private int yMax2;
private int xMin3 = 0; // This view's bounds
private int xMax3;
private int yMin3 = 0;
private int yMax3;
private float ballRadius = 80;
private float ballRadius2 = 80;// Ball's radius
private float ballX = ballRadius + 20; // Ball's center (x,y)
private float ballY = 10;//ballRadius + 40;
private float ballX1= ballRadius2 + 30;
private float ballY1 = 15;
private float ballX2 = ballRadius + 20; // Ball's center (x,y)
private float ballY2 = 10;//ballRadius + 40;
private float ballX3 = ballRadius + 20; // Ball's center (x,y)
private float ballY3 = 10;//ballRadius + 40;
private float ballSpeedX = 50; // Ball's speed (x,y)
private float ballSpeedX1= 25;
private float ballSpeedY = 30;
private float ballSpeedY1= 15;
private float ballSpeedX2 = 40; // Ball's speed (x,y)
private float ballSpeedX3= 20;
private float ballSpeedY2 = 20; // Ball's speed (x,y)
private float ballSpeedY3= 10;
private RectF ballBounds; // Needed for Canvas.drawOval
private RectF ballBounds2;
private RectF ballBounds3;
private RectF ballBounds4;
private Paint paint; // The paint (e.g. style, color) used for drawing
// Constructor
public BouncingBallView(Context context) {
super(context);
ballBounds = new RectF();
ballBounds2 = new RectF();
ballBounds3 = new RectF();
ballBounds4 = new RectF();
paint = new Paint();
}
// Called back to draw the view. Also called by invalidate().
#Override
protected void onDraw(Canvas canvas) {
ballBounds2.set(10, ballY1, 50, ballY1+40);
paint.setColor(Color.BLUE);
canvas.drawRoundRect(ballBounds2,6,6, paint);
// Draw the ball
ballBounds.set(10, ballY, 50, ballY+40);
paint.setColor(Color.RED);
canvas.drawRoundRect(ballBounds,6,6, paint);
ballBounds3.set(10, ballY2, 50, ballY2+40);
paint.setColor(Color.YELLOW);
canvas.drawRoundRect(ballBounds3,6,6, paint);
ballBounds4.set(10, ballY3, 50, ballY3+40);
paint.setColor(Color.GREEN);
canvas.drawRoundRect(ballBounds4,6,6, paint);
// Update the position of the ball, including collision detection and reaction.
update();
// Delay
try {
Thread.sleep(30);
} catch (InterruptedException e) { }
invalidate(); // Force a re-draw
}
// Detect collision and update the position of the ball.
private void update() {
// Get new (x,y) position
//ballX += ballSpeedX;
ballY += ballSpeedY;
ballY1 += ballSpeedY1;
ballY2 += ballSpeedY2;
ballY3 += ballSpeedY3;
// Detect collision and react
// if (ballX + ballRadius > xMax) {
// ballSpeedX = -ballSpeedX;
// ballX = xMax-ballRadius;
// }
// else if (ballX - ballRadius < xMin) {
// ballSpeedX = -ballSpeedX;
// ballX = xMin+ballRadius;
// }
if (ballY + ballRadius > yMax) {
ballSpeedY = -ballSpeedY;
ballY = yMax - ballRadius;
} else if (ballY - ballRadius < yMin) {
ballSpeedY = -ballSpeedY;
ballY = yMin + ballRadius;
}
if (ballY1 + ballRadius2 > yMax1) {
ballSpeedY1 = -ballSpeedY1;
ballY1 = yMax1 - ballRadius2;
} else if (ballY1 - ballRadius2 < yMin1) {
ballSpeedY1 = -ballSpeedY1;
ballY1 = yMin1 + ballRadius2;
}
if (ballY2 + ballRadius2 > yMax2) {
ballSpeedY2 = -ballSpeedY2;
ballY2 = yMax2 - ballRadius2;
} else if (ballY2 - ballRadius2 < yMin2) {
ballSpeedY2 = -ballSpeedY2;
ballY2 = yMin2 + ballRadius2;
}
if (ballY3 + ballRadius2 > yMax3) {
ballSpeedY3 = -ballSpeedY3;
ballY3 = yMax3 - ballRadius2;
} else if (ballY3 - ballRadius2 < yMin3) {
ballSpeedY3 = -ballSpeedY3;
ballY3 = yMin3 + ballRadius2;
}
}
// Called back when the view is first created or its size changes.
#Override
public void onSizeChanged(int w, int h, int oldW, int oldH) {
// Set the movement bounds for the ball
xMax = w-1;
yMax = h-1;
xMax1= w-1;
yMax1= h-1;
xMax2 = w-1;
yMax2 = h-1;
xMax3 = w-1;
yMax3 = h-1;
}
}
This code goes inside of your constructor.
ArrayList<RectF> ballBoundArray = new ArrayList<RectF>();
ballBoundArray.add(ballBounds);
ballBoundArray.add(ballBounds2);
ballBoundArray.add(ballBounds3);
ballBoundArray.add(ballBounds4);
Edit: If you want the array list to be accessible outside of the constructor, define it as a private or public variable with the other ballbounds.
Related
I was working on a brick breaker game in proccessing, and was trying to create the collision system for the game. I was able to identify when a collision happens between the ball and the brick, but I was not able to to make the brick dissapear when it gets hit by the ball. How do I do this? I would also appreciate a explanation, as I am a beginner.
Thanks.
color black = color(0,0,0);
color red = color(255,0,0);
color white = color(255,255,255);
float ballx = 412.5, bally = 600, balld = 20, ballr = balld/2, paddleX = 362.5, paddleY = 650;
float paddleW = 100, paddleH = 15;
float ballspdX, ballspdY;
boolean ball_drop = true;
float direction_choice;
float[] brickX = new float[10];
float[] brickY = new float[5];
float brickW = 50, brickH = 25;
void setup(){
size(825,800);
surface.setTitle("Brick breaker");
noCursor();
smooth();
brickX[0] = 50;
brickX[1] = 125;
brickX[2] = 200;
brickX[3] = 275;
brickX[4] = 350;
brickX[5] = 425;
brickX[6] = 500;
brickX[7] = 575;
brickX[8] = 650;
brickX[9] = 725;
brickY[0] = 50;
brickY[1] = 125;
brickY[2] = 200;
brickY[3] = 275;
brickY[4] = 350;
}
void paddle(){
noStroke();
fill(white);
rect(paddleX, paddleY, paddleW, paddleH);
}
void ball(){
noStroke();
fill(red);
circle(ballx, bally, balld);
}
void draw(){
background(black);
paddle();
ball();
if (bally + ballr == paddleY && ballx > paddleX && ballx < paddleX + (paddleW / 2)){
ball_drop = false;
ballspdY = -ballspdY;
ballspdX = -4;
}
/*
if (bally + ballr == paddleY && ballx > paddleX && ballx < paddleX + paddleW){
ball_drop = false;
ballspdY = -ballspdY;
direction_choice = int(random(1,3));
if (direction_choice == 1){
ballspdX = 4;
}
if (direction_choice == 2){
ballspdX = -4;
}
}
println(direction_choice);
*/
if (bally + ballr == paddleY && ballx > paddleX + (paddleW /2) && ballx < paddleX + paddleW){
ball_drop = false;
ballspdY = -ballspdY;
ballspdX = 4;
}
if (ballx + ballr > width || ballx - ballr < 0){
ballspdX = -ballspdX;
}
if (bally - ballr < 0){
ballspdY = -ballspdY;
}
if (ball_drop){
ballspdX = 0;
ballspdY = 1;
}
for (int i = 0; i < brickX.length; i ++){
for(int j = 0; j < brickY.length; j ++){
fill(red);
rect(brickX[i], brickY[j], brickW, brickH);
if (collideLineCircle(brickX[i], brickY[j] + brickH, brickX[i] + brickW, brickY[j] + brickH, ballx, bally, ballr)){
ballspdY = -ballspdY;
}
}
}
if (bally >= 800){
bally = 600;
ballx = 412.5;
ball_drop = true;
}
bally += ballspdY;
ballx += ballspdX;
}
boolean collideLineCircle(float x1, float y1, float x2, float y2, float cx, float cy, float cr){
float A = y2 - y1, B = x1 - x2, C = x2*y1 - x1+y2;
float denom = A+A + B*B;
if (denom == 0){
return dist(x1,y1, cx, cy) < cr;
}
float Ix = (B*B*cx-A*B*cy - A*C)/denom, Iy = (A*A*cy-A*B*cx - B*C)/denom;
if (Ix >= min(x1,x2) && Ix <= max(x1,x2) & Iy >= min(y1,y2) && Iy <= max(y1,y2)) {
return abs (A*cx + B*cy + C)/sqrt(denom) < cr;
}
float d1 = dist(x1,y1,cx,cy), d2 = dist(x2,y2,cx,cy);
return min(d1,d2) < cr;
}
void mouseMoved(MouseEvent evt){
paddleX = evt.getX();
}
There are a number of ways this can be done. Perhaps the simplest change, given the data structures you already have is to create another array, this time a boolean array, and call it something like brickIsVisible.
Then you can use a simple if statement, e.g., if (brickIsVisible[i]) in your loops to determine how to color the brick. The same variable can be used to tell whether or not to do a collision test between the ball and the brick.
As for the coloring itself, there are a couple options.
I'm not sure how you are drawing your board. If you redraw the entire board with each gameloop frame, then presumably you first draw the background (which covers over the bricks) and then you draw the bricks. If this what is happening, then if brickIsVisible[i] is false you can simply omit drawing that brick on top of the background.
Another technique that is sometimes used is to make use of a transparent color. This is done by adding an alpha channel value to the color definition. Thus there are four variables instead of three. They are referred to as RGBA instead of RGB. If the fourth variable is 0, the color will be transparent. If it is 255 it will be fully visible. Intermediate values in sequence can be used if you want to create a fade in or fade out.
I am guessing you are using java.awt.Color. Following is an example that uses the four argument constructor, with the fourth being the alpha channel.
Color invisiblePurple = new Color(255, 0, 255, 0);
If the color is invisible, the RGB values don't really matter.
These days I mostly use JavaFX for graphics, so I might not be up on all the tricks of the trade with AWT/Swing. With JavaFX, one can directly set an opacity property for a graphic being displayed, which is pretty convenient. I think part of the reason that this is available in JavaFX is that screen graphics are structured more like a DOM tree (like an HTML domain object model), and the redrawing is handled behind the scenes on the current state of the tree, rather than explicitly for each object, as it is with AWT/Swing.
Another possible technique shown below uses a brick class array. The class has a 'show' boolean associated with it and the bricks are only displayed when brick[id].show is true. In this demo when the brick is selected with a mouse brick[id].show is set to false and that brick is not displayed. For your project you would have to do this when a brick is hit by the ball.
/*
Creates a grid of rectangles from a Brick class array.
Syntax: brick[id] = new Brick( x, y, w, h, "title", bkgrndColor, txtColor);
ID is taken from position in array.
*/
final int _brickGridX = 40;
final int _brickGridY = 60;
final int _brickW = 120;
final int _brickH = 60;
color BLUE = color(64, 124, 188);
color LTGRAY = color(185, 180, 180);
color YELLOW = color(245, 250, 13);
color RED = color(255, 0, 0);
color BLACK = color(0, 0, 0);
color WHITE = color(255, 255, 255);
Brick[] brick;
class Brick {
float x, y, w, h;
String title;
color bkgrnd;
color txtColor;
boolean show;
// Constructor
Brick(int xpos, int ypos, float wt, float ht, String titleStr, color background, color foreground) {
x = xpos;
y = ypos;
w = wt;
h = ht;
title = titleStr;
bkgrnd = background;
txtColor = foreground;
}
void display(int id) {
if (brick[id].show) {
fill(bkgrnd); // background color
stroke(0);
rect(x, y, w, h);
fill(txtColor); // text color
textSize(42);
textAlign(CENTER, CENTER);
text(title, x, y, w, h);
}
}
void press(int id) {
println("brick id = ", id + ": show =", brick[id].show);
}
}
void brickGrid() {
int left = 0;
int top = 0;
int vg = 0; // Space between cols (vert.gutter)
int hg = 0; // Space between rows (horz.gutter)
int rows = 5;
int cols = 5;
int id = 0;
brick = new Brick[rows*cols]; // creates brick array
for (int k = 0; k < cols; k++) {
for (int j = 0; j < rows; j++) {
left = _brickGridX + j * (_brickW + vg);
top = _brickGridY + k * (_brickH + hg);
brick[id] = new Brick(left, top, _brickW, _brickH, str(id), LTGRAY, BLACK);
brick[id].show = true;
id++;
}
}
}
void setup() {
size(800, 600);
background(BLUE);
brickGrid();
}
void draw() {
background(BLUE);
for (int i = 0; i < brick.length; i++) {
brick[i].display(i);
}
}
void mousePressed() {
for (int i = 0; i < brick.length; i++) {
if ((mouseX >= brick[i].x) && (mouseX <= brick[i].x + _brickW) && (mouseY >= brick[i].y) && (mouseY <= brick[i].y + _brickH)) {
brick[i].show = false;
// brick[i].press(i);
}
}
}
I am trying to make the drawRedlines function appear and disappear inside the mousePressed function and mouseReleased function. I have tried using background(255); in my mouseReleased but it also removes my crossBars function for some reason. I tried changing the cords for the redLine rect's to 0 but it still is in the same position when I release the mouse.
final int NUM_LINES = 15;
final int LINE_THICK = 20;
final int CONVERGE_VERTICAL_OFFSET = 175;
final int CONVERGE_VERTICAL_OFFSET2 = 100;
int capSize = 20;
int width = 500;
int height = 500;
int x1 = 30;
int crossWidth = width - (30*2);
int y1 = height - 20;
int crossHeight = 20;
int capX = x1;
int capY = y1 + crossHeight/2;
int capX2 = width - x1;
int diffY = 60;
int diffX = 10;
int redLinex = 145;
int redLinex2 = 350;
int redLiney = 0;
int redlineHeight = height;
int redlineWidth = 5;
void setup(){
size(500,500);
drawConvergingvertical();
horizontalCross();
drawYellowlines();
}
void draw(){
}
void mousePressed(){
drawRedlines();
}
void mouseReleased(){
drawConvergingvertical();
horizontalCross();
drawYellowlines();
}
void horizontalCross(){
for(int rows = 0; rows < NUM_LINES; rows++){
//println(rows, capX, capX2); Used this to Debug;
drawCrossbars();
y1 = y1 - diffY;
capY = capY - diffY - 1;
x1 = x1 + diffX;
capX = capX + diffX;
crossWidth = crossWidth - diffX*2;
capX2 = capX2 - diffX;
crossHeight = crossHeight - 2;
capSize = capSize - 2;
}
}
void drawCrossbars(){
rect(x1,y1,crossWidth,crossHeight);
ellipse(capX,capY,capSize,capSize);
ellipse(capX2,capY,capSize,capSize);
}
void drawConvergingvertical(){
fill(0);
stroke(0);
quad(width/2-CONVERGE_VERTICAL_OFFSET,height,width/2-CONVERGE_VERTICAL_OFFSET2,0,width/2-CONVERGE_VERTICAL_OFFSET2+LINE_THICK,0,width/2-CONVERGE_VERTICAL_OFFSET+LINE_THICK,height);
quad(width/2+CONVERGE_VERTICAL_OFFSET,height,width/2+CONVERGE_VERTICAL_OFFSET2,0,width/2+CONVERGE_VERTICAL_OFFSET2-LINE_THICK,0,width/2+CONVERGE_VERTICAL_OFFSET-LINE_THICK,height);
}
void drawYellowlines(){
fill(255,255,0);
stroke(255,255,0);
rect(150, height - 100, 200, 10);
rect(150, 100, 200, 10);
}
void drawRedlines(){
redLinex = 145;
redLinex2 = 350;
redLiney = 0;
redlineHeight = height;
redlineWidth = 5;
fill(255,0,0);
stroke(255,0,0);
rect(redLinex,redLiney,redlineWidth,redlineHeight);
rect(redLinex2,redLiney,redlineWidth,redlineHeight);
}
How to remove a shape without using background(255); [...]
Not at all. You cant "remove" something what is drawn in the window. All you can do is to draw something different, what covers the shape. background doesn't remove anything. It just draws an uniform color in the entire window.
You've to redraw the entire scene in draw().
Use the built-in variable mousePressed to identify if the mouse is pressed and call drawRedlines() dependent on the state of the variable. Furthermore you've to reset the state of some variables in in every frame:
void draw() {
capSize = 20;
x1 = 30;
crossWidth = width - (30*2);
y1 = height - 20;
crossHeight = 20;
capX = x1;
capY = y1 + crossHeight/2;
capX2 = width - x1;
diffY = 60;
diffX = 10;
redLinex = 145;
redLinex2 = 350;
redLiney = 0;
redlineHeight = height;
redlineWidth = 5;
background(200);
drawConvergingvertical();
horizontalCross();
drawYellowlines();
if (mousePressed) {
drawRedlines();
}
}
Note, it is not necessary to draw anything in the mouse callback functions mousePressed respectively mouseReleased.
void mousePressed(){
}
void mouseReleased(){
}
Side note: Remove declaration of the variables width and height from your code. This are built-in variables, so it is not necessary to declare them at all, especially since the dependent variables are set in draw.
int width = 500;
int height = 500;
The draw() method is a loop. If you draw your stuff inside that loop, you can update it in real time. I modified your loop a little bit so the red lines appears only while the left mouse button si down:
final int NUM_LINES = 15;
final int LINE_THICK = 20;
final int CONVERGE_VERTICAL_OFFSET = 175;
final int CONVERGE_VERTICAL_OFFSET2 = 100;
int capSize = 20;
int width = 500;
int height = 500;
int x1 = 30;
int crossWidth = width - (30*2);
int y1 = height - 20;
int crossHeight = 20;
int capX = x1;
int capY = y1 + crossHeight/2;
int capX2 = width - x1;
int diffY = 60;
int diffX = 10;
int redLinex = 145;
int redLinex2 = 350;
int redLiney = 0;
int redlineHeight = height;
int redlineWidth = 5;
boolean redLineVisible = false;
void setup(){
size(500,500);
//drawConvergingvertical();
//horizontalCross();
//drawYellowlines();
}
void draw(){
background(255);
drawConvergingvertical();
horizontalCross();
drawYellowlines();
drawRedlines();
}
void mousePressed(){
//drawRedlines();
redLineVisible = true;
}
void mouseReleased(){
//drawConvergingvertical();
//horizontalCross();
//drawYellowlines();
//drawRedlines();
redLineVisible = false;
}
void horizontalCross(){
for(int rows = 0; rows < NUM_LINES; rows++){
//println(rows, capX, capX2); Used this to Debug;
drawCrossbars();
y1 = y1 - diffY;
capY = capY - diffY - 1;
x1 = x1 + diffX;
capX = capX + diffX;
crossWidth = crossWidth - diffX*2;
capX2 = capX2 - diffX;
crossHeight = crossHeight - 2;
capSize = capSize - 2;
}
}
void drawCrossbars(){
rect(x1,y1,crossWidth,crossHeight);
ellipse(capX,capY,capSize,capSize);
ellipse(capX2,capY,capSize,capSize);
}
void drawConvergingvertical(){
fill(0);
stroke(0);
quad(width/2-CONVERGE_VERTICAL_OFFSET,height,width/2-CONVERGE_VERTICAL_OFFSET2,0,width/2-CONVERGE_VERTICAL_OFFSET2+LINE_THICK,0,width/2-CONVERGE_VERTICAL_OFFSET+LINE_THICK,height);
quad(width/2+CONVERGE_VERTICAL_OFFSET,height,width/2+CONVERGE_VERTICAL_OFFSET2,0,width/2+CONVERGE_VERTICAL_OFFSET2-LINE_THICK,0,width/2+CONVERGE_VERTICAL_OFFSET-LINE_THICK,height);
}
void drawYellowlines(){
fill(255,255,0);
stroke(255,255,0);
rect(150, height - 100, 200, 10);
rect(150, 100, 200, 10);
}
void drawRedlines(){
if (redLineVisible) {
redLinex = 145;
redLinex2 = 350;
redLiney = 0;
redlineHeight = height;
redlineWidth = 5;
fill(255,0,0);
stroke(255,0,0);
rect(redLinex,redLiney,redlineWidth,redlineHeight);
rect(redLinex2,redLiney,redlineWidth,redlineHeight);
}
}
Have fun.
I am trying to add a square to the canvas when a mouse key is pressed and i want it to remain on the canvas when the mouse key is released, but it disappears when is released the key. Can anybody help me, what am i doing wrong?
int squareSize = 6;
final float DIFF_SIZE = 1;
final int MIN_COLOUR = 1;
final int MAX_COLOUR = 10;
final float INIT_RED = 100, INIT_GREEN = 50, INIT_BLUE = 80;
final float FINAL_RED = 255, FINAL_GREEN = 200, FINAL_BLUE = 250;
final float MAX_SIZE = 40;
final float X_SPACING = 10;
final float Y_SPACING = 10;
float squareX, squareY;
void setup() {
size(600, 600);
}
void draw() {
squareX = mouseX - squareSize / 2;
squareY = mouseY - squareSize / 2;
background(255);
drawRowsOfBlocks();
}
void drawOneBlock() {
rect(squareX, squareY, squareSize, squareSize);
for (int i = MIN_COLOUR; mousePressed && i <= MAX_COLOUR / 10; i++)
{
float redValue = INIT_RED + (i - MIN_COLOUR) / (MAX_COLOUR - MIN_COLOUR)(FINAL_RED - INIT_RED);
float greenValue = INIT_GREEN + (i - MIN_COLOUR) / (MAX_COLOUR - MIN_COLOUR)(FINAL_GREEN - INIT_GREEN);
float blueValue = INIT_BLUE + (i - MIN_COLOUR) / (MAX_COLOUR - MIN_COLOUR) * (FINAL_BLUE - INIT_BLUE);
fill(redValue, greenValue, blueValue);
rect(squareX, squareY, squareSize, squareSize);
squareSize += DIFF_SIZE;
}
if (squareSize > MAX_SIZE) {
squareSize = 6;
}
}
void drawRowsOfBlocks() {
drawOneBlock();
for (int i = 1; keyPressed && i <= 2; i++) {
drawOneBlock();
float squareY2;
squareY2 = squareY + squareSize + Y_SPACING;
squareY = squareY2;
}
}
Create a class which can handle a rectangle. The calls needs a method to draw the rectangle (Draw()) and a method to update the position and size of the rectangle (Update()):
final int DIFF_SIZE = 1;
final int MIN_SIZE = 6;
final int MAX_SIZE = 40;
final float INIT_RED = 100, INIT_GREEN = 50, INIT_BLUE = 80;
final float FINAL_RED = 255, FINAL_GREEN = 200, FINAL_BLUE = 250;
class Rectangle {
int pos_x, pos_y, size;
color col;
Rectangle(int px, int py, int s, color c) {
col = c;
pos_x = px; pos_y = py;
size = s;
}
void Update(int px, int py, int inc_size) {
pos_x = px; pos_y = py;
size += inc_size;
if (size > MAX_SIZE)
size = MIN_SIZE;
float w = float(size - MIN_SIZE) / float(MAX_SIZE - MIN_SIZE);
float redValue = INIT_RED + w * (FINAL_RED - INIT_RED);
float greenValue = INIT_GREEN + w * (FINAL_GREEN - INIT_GREEN);
float blueValue = INIT_BLUE + w * (FINAL_BLUE - INIT_BLUE);
col = color(int(redValue), int(greenValue), int(blueValue));
}
void Draw() {
fill(col);
rect(pos_x-size/2, pos_y-size/2, size, size);
}
}
Use ArrayList to store all the drawn rectangles:
ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
Add a global, boolean state (drawingRect) which indicates if the mouse button is currently pressed. Set the state and add new rectangle at the end of the list when the mousePressed() event occurs. rest the state when the mouseReleased() event occurs
boolean drawingRect = false;
void mousePressed() {
drawingRect = true;
color col = color(int(INIT_RED), int(INIT_GREEN), int(INIT_BLUE));
rectangles.add(new Rectangle(mouseX, mouseY, MIN_SIZE, col));
}
void mouseReleased() {
drawingRect = false;
}
Use the method .Update(), to change the location and size of the last rectangle in the list as long as the state drawingRect indicates that a mouse button is pressed.
Continuously draw all te rectangles in a loop:
void setup() {
size(600, 600);
}
void draw() {
if (drawingRect && rectangles.size() > 0) {
Rectangle lastRect = rectangles.get(rectangles.size()-1);
lastRect.Update(mouseX, mouseY, DIFF_SIZE);
}
background(255);
for (int i = 0; i < rectangles.size(); i++) {
Rectangle rect = rectangles.get(i);
rect.Draw();
}
}
I'm working in a spaceship first person view game. I have a joystick, and when i move the joystick i can move all the objects (asteroids) of the screen simulating that the spaceship is being moved with the joystick.
The game works fine, but now i have a problem. If you are pressing the joystick in the max left position and then you do ACTION_UP and then instantly ACTION_DOWN in the joystick again but in the max right position, the spaceship starts moving to the right at max speed. It is hard to explain it. For example, If you press the joystick in max left position the spaceship is moving -20px per frame to the left and if you press the joystick in the max right position, the spaceship moves to the right +20px per frame.
So, now, if i do a fast max left and max right touch on the joystick, the spaceship does this movement: -20....+20
It is not reallistic movement.
I want to get this movement: -20 -17 -14 -9 -5 0 +5 +9 +14 +17 +20.... I mean a more reallistic spaceship movement. But the problem is that i am not a math or physics expert, and i dont have any idea of how to get that kind of functionality in this joystick... any help will be very grateful.
Here you can find a demo project with the joystick: https://mega.co.nz/#!cp5FhYIT!dM88qx_xQdyhED9fX_4xeJ9ciQYJirUlNzEi-KOzU2k
This is the joystick code, i found it in google and works very well except for the non realistic movement that i described before:
public class Joystick extends View {
public static final int INVALID_POINTER = -1;
private JoystickMovedListener moveListener;
//# of pixels movement required between reporting to the listener
private float moveResolution;
//Max range of movement in user coordinate system
private float movementRange;
//Last touch point in view coordinates
private int pointerId = INVALID_POINTER;
private float touchX;
private float touchY;
private float touchXDelayedMovement;
private float touchYDelayedMovement;
//Handle center in view coordinates
private float handleX;
private float handleY;
//Last reported position in view coordinates (allows different reporting sensitivities)
private float reportX;
private float reportY;
//Center of the view in view coordinates
private int cX;
private int cY;
//Size of the view in view coordinates
private int dimX;
private int dimY;
private int innerPadding;
private int bgRadius;
private int handleRadius;
private int movementRadius;
private int handleInnerBoundaries;
//Cartesian coordinates of last touch point - joystick center is (0,0)
private int cartX;
private int cartY;
//User coordinates of last touch point
private int userX;
private int userY;
//Offset co-ordinates (used when touch events are received from parent's coordinate origin)
private int offsetX;
private int offsetY;
private Paint bgPaint;
private Paint handlePaint;
boolean disabled;
Handler handler;
Handler handlerDelayedMovement;
public Joystick(Context context) {
super(context);
initJoystickView();
}
private void initJoystickView() {
setFocusable(true);
handlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
handlePaint.setColor(Color.RED);
handlePaint.setStrokeWidth(1);
handlePaint.setStyle(Paint.Style.FILL_AND_STROKE);
bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bgPaint.setColor(Color.DKGRAY);
bgPaint.setStrokeWidth(1);
bgPaint.setStyle(Paint.Style.FILL_AND_STROKE);
this.moveResolution = 1.0f;
handler = new Handler();
handlerDelayedMovement = new Handler();
}
public void setMovementRange(float movementRange) {
this.movementRange = movementRange;
}
public void setOnJostickMovedListener(JoystickMovedListener listener) {
this.moveListener = listener;
}
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
int d = Math.min(getMeasuredWidth(), getMeasuredHeight());
dimX = d;
dimY = d;
cX = d / 2;
cY = d / 2;
bgRadius = dimX/2 - innerPadding;
handleRadius = (int)(d * 0.2);
handleInnerBoundaries = handleRadius;
movementRadius = Math.min(cX, cY) - handleInnerBoundaries;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Here we make sure that we have a perfect circle
int measuredWidth = measure(widthMeasureSpec);
int measuredHeight = measure(heightMeasureSpec);
setMeasuredDimension(measuredWidth, measuredHeight);
}
private int measure(int measureSpec) {
int result = 0;
// Decode the measurement specifications.
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.UNSPECIFIED) {
result = 200; // Return a default size of 200 if no bounds are specified.
} else {
result = specSize; // As you want to fill the available space always return the full available bounds.
}
return result;
}
#Override
protected void onDraw(Canvas canvas) {
canvas.save();
// Draw the background
canvas.drawCircle(cX, cY, bgRadius, bgPaint);
// Draw the handle
handleX = touchX + cX;
handleY = touchY + cY;
canvas.drawCircle(handleX, handleY, handleRadius, handlePaint);
canvas.restore();
}
public void setPointerId(int id) {
this.pointerId = id;
}
public int getPointerId() {
return pointerId;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_MOVE: {
if (disabled==true)
break;
return processMoveEvent(ev);
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP: {
if ( pointerId != INVALID_POINTER ) {
returnHandleToCenter();
returnHandleToCenterDelayedMovement();
setPointerId(INVALID_POINTER);
}
break;
}
case MotionEvent.ACTION_POINTER_UP: {
if ( pointerId != INVALID_POINTER ) {
final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if ( pointerId == this.pointerId ) {
returnHandleToCenter();
returnHandleToCenterDelayedMovement();
setPointerId(INVALID_POINTER);
return true;
}
}
break;
}
case MotionEvent.ACTION_DOWN: {
handlerDelayedMovement.removeCallbacksAndMessages(null);
if ( pointerId == INVALID_POINTER ) {
int x = (int) ev.getX();
if ( x >= offsetX && x < offsetX + dimX ) {
setPointerId(ev.getPointerId(0));
if (disabled==true){
return true;
}
return processMoveEvent(ev);
}
}
break;
}
case MotionEvent.ACTION_POINTER_DOWN: {
if ( pointerId == INVALID_POINTER ) {
final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
int x = (int) ev.getX(pointerId);
if ( x >= offsetX && x < offsetX + dimX ) {
setPointerId(pointerId);
return true;
}
}
break;
}
}
return false;
}
private boolean processMoveEvent(MotionEvent ev) {
if ( pointerId != INVALID_POINTER ) {
final int pointerIndex = ev.findPointerIndex(pointerId);
// Translate touch position to center of view
float x = ev.getX(pointerIndex);
touchX = x - cX - offsetX;
float y = ev.getY(pointerIndex);
touchY = y - cY - offsetY;
reportOnMoved();
invalidate();
return true;
}
return false;
}
private void reportOnMoved() {
//constraint circle
float diffX = touchX;
float diffY = touchY;
double radial = Math.sqrt((diffX*diffX) + (diffY*diffY));
if ( radial > movementRadius ) {
touchX = (int)((diffX / radial) * movementRadius);
touchY = (int)((diffY / radial) * movementRadius);
}
//We calc user coordinates
//First convert to cartesian coordinates
cartX = (int)(touchX / movementRadius * movementRange);
cartY = (int)(touchY / movementRadius * movementRange);
//Cartesian Coordinates
userX = cartX;
userY = cartY;
if (moveListener != null) {
boolean rx = Math.abs(touchX - reportX) >= moveResolution;
boolean ry = Math.abs(touchY - reportY) >= moveResolution;
if (rx || ry) {
this.reportX = touchX;
this.reportY = touchY;
moveListener.OnMoved(userX, userY);
}
}
}
private void reportOnMovedDelayedMovement() {
//constraint circle
float diffX = touchXDelayedMovement;
float diffY = touchYDelayedMovement;
double radial = Math.sqrt((diffX*diffX) + (diffY*diffY));
if ( radial > movementRadius ) {
touchXDelayedMovement = (int)((diffX / radial) * movementRadius);
touchYDelayedMovement = (int)((diffY / radial) * movementRadius);
}
//We calc user coordinates
//First convert to cartesian coordinates
cartX = (int)(touchXDelayedMovement / movementRadius * movementRange);
cartY = (int)(touchYDelayedMovement / movementRadius * movementRange);
//Cartesian Coordinates
userX = cartX;
userY = cartY;
if (moveListener != null) {
boolean rx = Math.abs(touchXDelayedMovement - reportX) >= moveResolution;
boolean ry = Math.abs(touchYDelayedMovement - reportY) >= moveResolution;
if (rx || ry) {
this.reportX = touchXDelayedMovement;
this.reportY = touchYDelayedMovement;
moveListener.OnMoved(userX, userY);
}
}
}
private void returnHandleToCenter() {
final int numberOfFrames = 5;
final double intervalsX = (0 - touchX) / numberOfFrames;
final double intervalsY = (0 - touchY) / numberOfFrames;
handler.removeCallbacksAndMessages(null);
for (int i = 0; i < numberOfFrames; i++) {
final int j = i;
handler.postDelayed(new Runnable() {
#Override
public void run() {
touchX += intervalsX;
touchY += intervalsY;
//reportOnMoved();
invalidate();
if (moveListener != null && j == numberOfFrames - 1) {
moveListener.OnReturnedToCenter();
}
}
}, i * 10);
}
if (moveListener != null) {
moveListener.OnReleased();
}
}
private void returnHandleToCenterDelayedMovement() {
final int numberOfFrames = 25;
touchXDelayedMovement=touchX;
touchYDelayedMovement=touchY;
final double intervalsX = (0 - touchXDelayedMovement) / numberOfFrames;
final double intervalsY = (0 - touchYDelayedMovement) / numberOfFrames;
handlerDelayedMovement.removeCallbacksAndMessages(null);
for (int i = 0; i < numberOfFrames; i++) {
handlerDelayedMovement.postDelayed(new Runnable() {
#Override
public void run() {
touchXDelayedMovement += intervalsX;
touchYDelayedMovement += intervalsY;
reportOnMovedDelayedMovement();
}
}, i * 50);
}
}
public void setInnerPadding(int innerPadding){
this.innerPadding=innerPadding;
}
public void disable(){
disabled=true;
}
public void enable(){
disabled=false;
}
public interface JoystickMovedListener {
public void OnMoved(int pan, int tilt);
public void OnReleased();
public void OnReturnedToCenter();
}
}
You must do this in the class that will use the joystick:
private JoystickMovedListener joystickListener = new JoystickMovedListener() {
#Override
public void OnMoved(int pan, int tilt) {
//here i move the objects in the game
}
}
#Override
public void OnReleased() {}
public void OnReturnedToCenter() {};
};
joystickOnScreen = new Joystick(this);
joystickOnScreen.setMovementRange(screenHeight/50);
joystickOnScreen.setInnerPadding(screenHeight/30);
joystickOnScreen.setOnJostickMovedListener(joystickListener);
RelativeLayout.LayoutParams joystickParams = new RelativeLayout.LayoutParams(sh/3, sh/3);
joystickParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
joystickParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
joystickParams.setMargins(sh/100, 0, 0, sh/100);
joystickOnScreen.setLayoutParams(joystickParams);
joystickOnScreen.setAlpha(0.3f);
I will not implement the changes for you but hopefully this answer can help you towards implementing this on your own.
With your current implementation you are updating the object position (x, y) each frame. To get the more realistic physics that you want, you need to store and update velocity as well (vx, vy).
Add two new variables, vx and vy (with initial values of zero) in the objects that you are currently updating the position for. The joystick should control the change of the velocity instead of the position. Change the code that updates the positions x and y, to update the velocities vx and vy instead. When the joystick is max left, you can for example set vx = vx - 3.
After the velocity is updated, you need to update the position using the velocity variables. For example, set the position x = x + vx. Ideally you want this to happen in a different method that runs even if you don't move the joystick, but to keep it simple you can do this update right after the update of the velocity variables.
With this implementation you will get a more realistic game physics. As a next step you might want to add limits on the velocity to not move too fast. This can be done with an if-statement where you check that the value is not too big before adding more to it, or too smal before subtracting from it. Good luck!
please help. I am new to android game development and java. I want my deer to loop or start from 0,0 again when it touches the border of the screen but i have no idea how to code it.
package com.cmanres.bunnyjourney;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
public class Spriteleft {
private static final int BMP_COLUMNS = 3;
private static final int BMP_ROWS = 2;
private int x = 0;
private int y=0;
private int xSpeed = 3;
private Levelunogame gameView;
private Bitmap deer1;
private int width;
private int height;
private int currentFrame=0;
public Spriteleft(Levelunogame gameView, Bitmap deer1) {
this.gameView=gameView;
this.deer1=deer1;
this.width = deer1.getWidth() / BMP_COLUMNS;
this.height = deer1.getHeight() / BMP_ROWS;
}
private void update() {
if (x > gameView.getWidth() - width - xSpeed) {
xSpeed = -3;
}
if (x + xSpeed< 0) {
xSpeed = 3;
}
x = x + xSpeed;
currentFrame = ++currentFrame % BMP_COLUMNS;
}
public void onDraw(Canvas canvas) {
update();
int srcX = currentFrame * width;
int srcY = 1 * height;
Rect src = new Rect(srcX, srcY, srcX + width, srcY + height);
Rect dst = new Rect(x, y, x + width, y + height);
canvas.drawBitmap(deer1, src , dst, null);
}
}
that is my code that i followed on a android mobile game tutorial. can anyone show me how to do it? or give any links for a tutorial? I will appreciate it very much.
Assuming your sprite is positioned at x, y with sprite_width, sprite_height
// Check if your sprite position is outside the screen bounds
if( x < 0 || x > gameView.getWidth() - sprite_width
|| y < 0 || y > gameView.getHeight() - sprite_height ) {
// Set x, y to 0,0
x = 0;
y = 0;
}