Update & DoDraw method to spawn multiple of the same sprite - java

I'm trying to spawn multiple versions of the same sprite. Each spawns with a random speed (using random numbers between minus and positive speeds to determine random direction) and I have created 2 for loops to load an arraylist with new sprites. However, it seems to spawn 5 sprites, but then it seems like they're deleting and creating 5 more over and over. Below are the methods used:
public void update(){
spritesArrayList.clear();
if (gameOver != true)
{
sprite.update();
}
for (int i = 0; i < count; i++)
{
sprite = new Sprite(this);
spritesArrayList.add(sprite);
}
}
/**
* To draw the game to the screen
* This is called from Thread, so synchronisation can be done
*/
public void doDraw(Canvas canvas) {
Paint textPaint = new Paint();
canvas.drawBitmap(mBackgroundImage, 0, 0, null);
//Draw all the objects on the canvas
canvas.drawText("The Game ",5,25, paint);
canvas.drawText("Score: " + hitCount, 5, 50, paint);
canvas.drawText("Time: " +displayTime, 5, 75, paint);
GetArrayListSize();
//Loop for sprite creation
for (int i = 0; i < arraySize; i++)
{
Sprite sprite = spritesArrayList.get(i);
sprite.draw(canvas);
}
if (gameOver == true)
{
canvas.drawText("Final Score: "+finalScore, 5,100, paint);
int width = this.getMeasuredWidth()/2;
int height = this.getMeasuredHeight()/2;
textPaint.setTextAlign(Align.CENTER);
canvas.drawText("GAME OVER - PRESS BACK BUTTON TO RETURN", width, height, textPaint);
}
}

Related

Using Ani Library on Objects (Processing)

I am currently working with the Ani Library in Processing.
I'm trying to fade in some rectangles one by one (on a PGraphics). To let the rectangles appear I use a loop - whose size I can control with MouseX. So one rectangle appears after the other. But I also want to fade in each one individually using the Ani Library. Currently I can only get the fade in to affect all of them at once.
So I tried to make an object out of the rectangle and put the FadeIn inside the object. But it behaves similar here – all fade in at once.
How can I solve this? Do I need an Array or an Array List for this?
This is my Code without an object:
import de.looksgood.ani.*;
PGraphics pg;
float alpha;
void setup() {
size(1920, 1920);
rectMode(CENTER);
Ani.init(this);
pg = createGraphics(width, height);
}
void draw() {
drawPG();
image(pg, 0,0);
}
void drawPG () {
pg.beginDraw();
pg.pushMatrix();
pg.translate(100, height/4.75);
pg.background(255);
pg.noStroke();
Ani.to(this, 10, "alpha", 255, Ani.EXPO_OUT);
color black = color(0, 0, 0, alpha);
pg.fill(black);
int blocks = int(map(mouseX, 0, width, 0, 7));
for (int i = 0; i < blocks; i++) {
pg.pushMatrix();
pg.translate(i * 200 + i*100, 0);
pg.rect(0, 0, 200, 200);
pg.popMatrix();
}
pg.popMatrix();
pg.endDraw();
}
And this is my tried out version with an Object:
import de.looksgood.ani.*;
PGraphics pg;
Rectangle myRect;
void setup() {
size(1920, 1920);
rectMode(CENTER);
myRect = new Rectangle();
Ani.init(this);
pg = createGraphics(width, height);
}
void draw() {
drawPG();
image(pg, 0,0);
}
void drawPG () {
pg.beginDraw();
pg.pushMatrix();
pg.translate(100, height/4.75);
pg.background(255);
pg.noStroke();
int blocks = int(map(mouseX, 0, width, 0, 7));
for (int i = 0; i < blocks; i++) {
pg.pushMatrix();
pg.translate(i * 200 + i*100, 0);
myRect.display(pg);
pg.popMatrix();
}
pg.popMatrix();
pg.endDraw();
}
class Rectangle {
float alpha;
Rectangle() {
}
void display(PGraphics pg) {
Ani.to(this, 10, "alpha", 255, Ani.EXPO_OUT);
color black = color(0, 0, 0, alpha);
pg.fill(black);
pg.rect(0, 0, 200, 200);
}
}
+++ EDIT +++
Found a solution here:
https://processing.org/tutorials/objects
And this gave me the hint to really work with an array. And then it says for the PGraphic:
void drawPG () {
pg.beginDraw();
pg.pushMatrix();
pg.translate(100, height/4.75);
pg.background(255);
pg.noStroke();
int blocks = int(map(mouseX, 0, width, 0, rectangles.length));
for (int i = 0; i < blocks; i++) {
pg.pushMatrix();
pg.translate(i * 200 + i*100, 0);
rectangles[i].display(pg);
pg.popMatrix();
}
pg.popMatrix();
pg.endDraw();
}
Above setup();
Rectangle[] rectangles = new Rectangle[7];
And in setup();
for (int i = 0; i < rectangles.length; i++) {
rectangles[i] = new Rectangle();
}

How show text in centre of each rectangle using onDraw

I'm trying to create a text view (black colour) containing numbers 1 to 7 (each number on top and in the centre of each grey rectangle - just like the image I've drawn below) but I'm not sure what properties I need to add in order to achieve this. I believe the code needs to go in the loop section but I don't what code. What can be done so that a number appears centralised in each grey rectangle?
desired outcome
current outcome
public class RectangleTextView extends View {
private final Paint mBackPaint = new Paint();
private final Paint mRedPaint = new Paint();
private int mSideRectWidth = 10;
public RectangleTextView(Context context, AttributeSet attrs) {
super(context, attrs);
mBackPaint.setColor(Color.BLACK);
mRedPaint.setColor(Color.RED);
}
#Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (getWidth() == 0)
return;
//draw grey boxes
setBackgroundColor(Color.parseColor("#808080"));
int boxWidth = getWidth() / 7;
//draw black lines and/or draw text in centre of each rectangle
for (int i = 0; i < 7; i++) {
canvas.drawLine(mSideRectWidth + boxWidth * i, 0, mSideRectWidth + boxWidth * i, getHeight(), mBackPaint);
canvas.drawText(?);
}
//draw text in centre of each rectangle
?
//draw left end rectangle
canvas.drawRect(0, 0, mSideRectWidth, getHeight(), mRedPaint);
//draw right end rectangle
canvas.drawRect(getWidth() - mSideRectWidth, 0, getWidth(), getHeight(), mRedPaint);
}
}
Use canvas.drawText(). You can do it in the same loop that you draw the black lines.
for (int i = 0; i < 7; i++) {
canvas.drawLine(mSideRectWidth + boxWidth * i, 0, mSideRectWidth + boxWidth * i, getHeight(), mBackPaint);
float x = ...
float y = ...
canvas.drawText(Integer.toString(i + 1), x, y, mBlackPaint);
}
You will have to figure out the x and y value for the placement of the text. If you use paint.setTextAlign(Align.CENTER), then that simplifies the x value calculation, it's just halfway between the black lines.
Use the Paint.getTextBounds() method to get the bounding area of the text, then the exact center vertically and horizontally can be extracted from the resulting Rect object:
Paint paint = new Paint();
paint.setTextSize( textSize );
Rect bounds = new Rect();
if( text != null )
paint.getTextBounds(text, 0, text.length(), bounds);
else
bounds.set(0,0,0,0);
location.x -= bounds.exactCenterX();
location.y -= bounds.exactCenterY();

Drawing the position indicator on the image

so, here is the question, i need to draw the position indicator corresponding to my hand position and then perform some manipulations on an image
here is the screen capture:
the left half of the screen is the image, and the right half of the screen is my camera,
the program will draw the position indicator corresponding to my hand position,
my problem is that the cursor cannot be disappeared and it will draw many times!
here is the code:
import gab.opencv.*;
import processing.video.*;
import java.awt.*;
PImage img;
PImage select;
PImage cur;
OpenCV opencv;
Capture cam;
int prevPositionX, prevPositionY, currPositionX, currPositionY;
int mode = -1; //mode 1 = s (select) mode 2 = c (copy) mode 3 = d (draw)
int select_ind = -1;
//store every dectected things
Rectangle[] hand;
//store the biggest hand
Rectangle bhand;
void setup() {
size(1280, 480);
img = loadImage("test.jpg");
cur = loadImage("cursor.png");
stroke(255,10,0);
opencv = new OpenCV(this, 640, 480);
opencv.loadCascade("aGest.xml");
cam = new Capture(this, 640, 480);
cam.start();
image(img, 0, 0, img.width, img.height);
}
void draw(){
if (cam.available()==true) {
cam.read();
}
opencv.loadImage(cam);
hand = opencv.detect();
pushMatrix();
scale(-1.0, 1.0);
image(cam, -1280, 0);
popMatrix();
int handcount = -1;
int handsize = -1;
//calculate the biggest hand
for( int i=0; i < hand.length; i++ ) {
if(handsize < (hand[i].width * hand[i].height)){
handsize = hand[i].width * hand[i].height;
handcount = 1;
bhand = hand[i];
}
}
if(handcount > 0){
rect(1280 - bhand.x, bhand.y, -bhand.width, bhand.height);
noFill();
//draw the position indicator
image(cur, 480 - bhand.x, bhand.y, 16, 16);
prevPositionX = currPositionX;
prevPositionY = currPositionY;
currPositionX = 480 - bhand.x + 4;
currPositionY = bhand.y;
//select mode
if (mode == 1){
}
//copy mode
else if (mode == 2){
}
//draw mode
else if (mode == 3){
line(prevPositionX,prevPositionY,currPositionX,currPositionY);
}
}
}
void keyPressed(){
if(key=='s'||key=='S')
mode = 1;
else if(key=='c'||key=='C')
mode = 2;
else if(key=='d'||key=='D')
mode = 3;
else if(key=='i'||key=='I')
image(img, 0, 0, img.width, img.height);
}
void keyReleased(){
if(select_ind > -1 && mode == 2){
//to be done
}
mode = -1;
}
i am working with the drawing mode which is to draw a line on the image,
and i know the problem but i do not know how to solve it,
i need to add this : image(img, 0, 0, img.width, img.height); to the first
of draw() function, but the line will also be deleted. i want to keep
the line like the screen capture.
Please give me a hand and sorry for the bad english. Thanks
If you need to persist just part of the draw, you need to redraw it every frame, while still "clearing" the background using image(img, 0, 0, img.width, img.height). This means store coordinates of lines and redraw it every time, also note that you can hide the cursor... SomeThing like this:
// YOU GOT ADD (CLICK) AT LEAST 2 POINTS TO SEE IT WORKING ;)
ArrayList<PVector> positions = new ArrayList<PVector>();
void setup(){
size(600, 600);
//if you don't want to see the cursor...
noCursor();
}
void draw(){
//clear screen
background(255);
//always draw at mousePosition
//a "custom cursor"
//that will not persist as screen is beeing cleared
fill(200,80,220);
noStroke();
ellipse(mouseX, mouseY, 20, 20);
stroke(80);
PVector prevP = null;
for (PVector p:positions) {
if(prevP != null) {
line(prevP.x, prevP.y, p.x, p.y);
}
prevP = p.get();
}
}
void mouseClicked() {
positions.add(new PVector(mouseX, mouseY));
}
EDIT:
Also you can use PGraphics as layers to persist just part of the drawing without redrawing all the stuff over and over... :)

How can I draw several rectangles in a row programmatically?

I want to put several rectangle i a row. But because I'm new to Android and specially to Bitmap, Canvas and so on, I need some help.
It should look like this, only with rectangles:
I have created one rectangle with this code:
Paint paint = new Paint();
paint.setColor(Color.parseColor("#CD5C5C"));
Bitmap bg = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bg);
canvas.drawRect(50, 80, 200, 200, paint);
RelativeLayout ll = (RelativeLayout) findViewById(R.id.rect);
ImageView iV = new ImageView(this);
iV.setImageBitmap(bg);
ll.addView(iV);
But now I dont know how to create more rectangles with different colors in a row.
I'm really new and sorry for that maybe stupid question but I need help for it.
Can anybody guide me how to do this in the best way?
The key here are these lines:
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawRect(50, 80, 200, 200, paint);
They set the colour and draw a rectangle. You can now repeat these lines to get 2 rectangles:
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawRect(50, 80, 200, 200, paint);
paint.setColor(Color.parseColor("#DDDDDD"));
canvas.drawRect(210, 80, 360, 200, paint);
Note that I have changed the colour and co-ordinates a little bit. You could continue doing this several times to get all of your rectangles drawn.
Better still use a variable for the x and y coordinates, and use a loop:
int left = 50; // initial start position of rectangles (50 pixels from left)
int top = 50; // 50 pixels from the top
int width = 150;
int height = 150;
for (int row = 0; row < 2; row++) { // draw 2 rows
for(int col = 0; col < 4; col++) { // draw 4 columns
paint.setColor(Color.parseColor("#CD5C5C"));
canvas.drawRect(left, top, left+width, top+height, paint);
left = (left + width + 10); // set new left co-ordinate + 10 pixel gap
// Do other things here
// i.e. change colour
}
top = top + height + 10; // move to new row by changing the top co-ordinate
}
Hope that helps.
This should do it. I tried to self-document my code as mush as possible. This is very dynamic i.e. you can adjust the height, width, xPad, yPad, etc. and the window will compensate.
import java.awt.*;
import java.util.Random;
import javax.swing.*;
public class RectanglesPanel extends JPanel {
public static final int[] COLORS = new int[] {
0xFFFFFF, 0xF67457, 0xFFC238, 0xEFEF38,
0xBCCACA, 0x75D1E0, 0x84E0C2, 0xC2E749
};
private static Random rand = new Random();
private int width = 80;
private int height = 50;
private int rows = 2;
private int cols = 4;
private int xPad = 20;
private int yPad = 30;
private float strokeWidth = 2.0f;
int windowWidth = calculateOffset(width, cols, xPad);
int windowHeight = calculateOffset(height, rows, yPad);
public RectanglesPanel() {
setPreferredSize(new Dimension(windowWidth, windowHeight));
}
private int calculateOffset(int whole, int partitions, int padding) {
return (whole * partitions) + (padding * (partitions + 1));
}
#Override
public void paintComponent(Graphics g) {
Stroke stroke = new BasicStroke(strokeWidth,
BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER);
((Graphics2D)g).setStroke(stroke);
// Fill in background.
g.setColor(new Color(0xF6F6F6));
g.fillRect(0, 0, windowWidth, windowHeight);
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
int x = calculateOffset(width, col, xPad);
int y = calculateOffset(height, row, yPad);
int color = (row * cols + col) % COLORS.length;
// Fill in rectangle.
g.setColor(new Color(COLORS[color]));
g.fillRect(x, y, width, height);
// Stroke the border of the rectangle.
g.setColor(new Color(0xE7E7E7));
g.drawRect(x, y, width, height);
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new RectanglesPanel();
frame.setContentPane(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
use for loop keeping the y coordinates constant
for(i=0;i<=200;i=i+40)
{
canvas.drawRect(i,0,i+30,100);
}
for next row increase y coordinate by your require amount and repeat the same or use nested for loops
you can set color by
myPaint.setColor(color.black);
myPaint.setStyle(Style.FILL);
canvas.drawRect(0,0,100,100, myPaint);

flickering android screen once drawing using a loop libgdx

im drawing a basic grid using a nested for loop (libgdx) but when i test it on android it keeps on flickering i have tried many different ways but still cant get it to stop the flickering.. here is my code
public void create() {
rend = new ShapeRenderer();
screenH = Gdx.graphics.getHeight();
screenH = (int) (screenH*(0.32));
System.out.println(screenH);
screenW = Gdx.graphics.getWidth();
screenW = (int) (screenW*(0.322));
System.out.println(screenW);
batch = new SpriteBatch();
dots = new Rectangle();
storeV();
render method
public void render() {
Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1);
//Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
rend.begin(ShapeType.Filled);
batch.setColor(Color.WHITE);
rend.rect(100, 100, 200, 200);
for (int i=0; i<4; i++){
for (int j=0;j<4;j++){
//batch.draw(dot, posx, posy);
rend.setColor(Color.WHITE);
rend.rect(posx, posy, 16, 16);
posx+=screenW;
}
posx=0;
rend.rect(posx, posy, 16, 16);
// batch.draw(dot, posx, posy);
posy+=screenH;
}
rend.end();
batch.begin();
batch.end();
}
as you see i have tried drawing a rectangle and using a texture but both happen to flicker. the rectangle drawn outside the loop dosent flicker.
and here is my storeV()
public void storeV(){
for (int i=0; i<4; i++){
Xpoints[i]+=screenW*i;
}
for (int i=0; i<4; i++){
Ypoints[i]+=screenH*i;
}

Categories

Resources