How do I use mouselistener and press event to change a filled square to another color? - swing

This is for homework, I have most of this done but I am stuck on the final step (implementing a mouse event that will change one of my randomized colored squares to become red instead of it's assigned colors) and am concerned that using the methods provided by my prof are not suitable to this, as he has us repaint after mouse event (which I feel my code will just override with more random colors). Any assistance or nudge in the right direction would be helpful, and I am sure this is a mess.
Update as per Camickr's assistance, my code has changed to the following:
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.*;
// MouseListener Imports
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
public class Test extends JPanel implements MouseListener
{
static Color[][] framework = new Color[8][8];
static int redCounter = 0;
// main Creates a JFrame and instantiates the 2d array of color objects
public static void main(String[] args)
{
// The frame handles all the outside window work
JFrame frame = new JFrame("MouseListener demo");
// Allows the 'X' in the upper right to cause the program to exit
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
// contentPane holds a panel
JComponent newContentPane = new Test();
// MouseListenerDemo isa JPanel isa JComponent
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
/* Causes this Window to be sized to fit the preferred size and layouts of its subcomponents.
The resulting width and height of the window are automatically enlarged if either of dimensions
is less than the minimum size as specified by the previous call to the setMinimumSize method.
If the window and/or its owner are not displayable yet, both of them are made displayable before
calculating the preferred size. The Window is validated after its size is being calculated.
*/
frame.setVisible(true);
for (int x = 0; x < framework.length; x++) {
for (int y = 0; y < framework.length; y++) {
Color rc = randomColor();
framework[x][y] = rc;
}
}
}
// Constructor
public Test()
{
// layout the panel with an area in which to draw
super(new GridLayout(0,1));
// get Graphics object, which allows you to draw on the panel
// set initial size of the panel
setPreferredSize(new Dimension(400, 500));
// ADD this JPanel to the list of components notified when a mouse event happens
this.addMouseListener(this);
// calls paint()
repaint();
}
// draws the screen
public void paint(Graphics g)
{
// Get the size
Dimension d = this.getSize();
int size = 50; // The edge length of the squares
int xSt = 50; // Starting x-coordinate
int ySt = 50; // Starting y-coordinate
int n = 8; // n X n board
int xPos, yPos;
for(int row = 0; row < framework.length; row ++){
for (int col = 0; col < framework.length; col ++){
xPos = xSt*col;
yPos = xSt*row;
// set color
g.setColor (framework[row][col]);
// Draw square
g.fillRect(xPos, yPos, size, size);
}
}
g.setColor(Color.black);
g.drawString("There are " + redCounter + " reds." , d.width/3, d.height);
}
public static Color randomColor(){
Random rg = new Random();
int result = rg.nextInt(12);
Color color;
switch(result){
case 0: color = Color.black;
break;
case 1: color = Color.blue;
break;
case 2: color = Color.cyan;
break;
case 3: color = Color.darkGray;
break;
case 4: color = Color.yellow;
break;
case 5: color = Color.green;
break;
case 6: color = Color.lightGray;
break;
case 7: color = Color.magenta;
break;
case 8: color = Color.orange;
break;
case 9: color = Color.pink;
break;
case 10: color = Color.red; redCounter = redCounter + 1;
break;
case 11: color = Color.white;
break;
default: color = Color.black;
break;
}
return color;
}
// MouseListener methods
public void mousePressed(MouseEvent evt)
{
// demonstrates how to use the parameter
// to get the position of the mouse press
Dimension d = this.getSize();
int x = evt.getX();
int y = evt.getY();
System.out.println(x+","+y);//these co-ords are relative to the component
System.out.println(evt.getSource());
for (int i = 0; i < framework.length; i++) {
for (int j = 0; j < framework.length; j++) {
System.out.println(framework[i][j]);
if (evt.getSource().equals(framework[i][j])) {
framework[i][j] = Color.red;
redCounter = redCounter + 1;
}
}
}
repaint(); // redisplay the frame by eventually calling the paint() method
}
// do nothing for the other mouse actions
public void mouseReleased(MouseEvent evt) {}
public void mouseClicked(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
}

am concerned that using the methods provided by my prof are not suitable to this, as he has us repaint after mouse event (which I feel my code will just override with more random colors).
The repaint() in the MouseEvent is correct. However more random colors will be generated because your painting code is incorrect.
A painting method should only paint the state of your component, not change the state. Therefore:
You need to keep a data structure (lets say a 2D array) to hold the Color of each cell. In the constructor of your class you would then iterate through this array and assign the random colors to each entry in the array.
Then in the painting method you just iterate through the array and paint each cell using the color from the array.
Note you should be overriding paintComponent(), not paint() for the custom painting.
Then in your MouseListener code you just reset the Color in the Array for the cell that was clicked and invoke repaint().

I fixed it by getting the position of x/y and dividing them by 50 (my square height/width) and putting the int into the array index.
public void mousePressed(MouseEvent evt)
{
// demonstrates how to use the parameter
// to get the position of the mouse press
Dimension d = this.getSize();
int x = evt.getX()/50;
int y = evt.getY()/50;
framework[y][x] = Color.red;
redCounter = redCounter+1;
repaint(); // redisplay the frame by eventually calling the paint() method
}

Related

How to create a matrix in a loop for hittesting with colors without duplicate colors

I am trying to create a matrix with color hexagons that will allow for object hit-testing. This color matrix will sit behind a regular hexagon matrix(one without the matrix cells colored). I will mouse over and check for the color in the hidden matrix to indicate which object my mouse is over so I can simulate object detection. This should be straight forward but for some reason I cannot get the expected results.
I have a parent loop which loops through creating rows of the matrix. Each iteration calls the following function to paint the hexagon(which is defined in a collection of points made available through a hexagon service).
constructor(
private hexagons: HexagonService,
private state: StateService,
private randomColors: RandomColorService,
private drawingContextService: DrawingContextService) {
}
async DrawHexagonAsync(hidecolors: boolean): Promise<any> {
const color = this.randomColors.next();
let strokestyle = this.state.strokeStyle;
const context = this.drawingContextService.context;
console.log(color); // Look for duplicates in console
if (hidecolors) {
strokestyle = `#fff`;
}
context.strokeStyle = strokestyle;
context.lineWidth = this.state.lineWidth;
context.fillStyle = color;
context.lineJoin = 'round';
context.lineCap = 'round';
const points = this.hexagons.getHexagonPoints();
context.beginPath();
let x = this.drawingContextService.location.x + points[0].x;
let y = this.drawingContextService.location.y + points[0].y
context.moveTo(x,y);
// move to the start point
for (let i = 1; i < points.length; i++) {
x = points[i].x + this.drawingContextService.location.x;
y = points[i].y + this.drawingContextService.location.y;
context.lineTo(x, y);
context.stroke();
}
context.fill();
context.closePath();
}
At first glance it looks like it is working and creates a lovely hex matrix like the following:
At closer inspection, I noticed that some of the contiguous items get rendered as duplicate colors. Since, I need unique colors for hit-testing this will not do. I use a color service to iterate through and create unique colors.
// color service.
#Injectable({provideIn: 'root'})
export class RandomColorService {
colors: string[] = [];
index = 0;
constructor() {
while (this.colors.length < 5000) {
let random = () => {
let n = Math.random() * 256;
return Math.floor(n).toString(16);
}
// make sure there are no duplicate colors.
const color = `#${random()}${random()}${random()}`;
if (!this.colors.includes(color)) {
this.colors.push(color);
}
}
}
public next() {
if (this.index >= 5000) {
this.index = 0;
}
return this.colors[this.index++];
}
}
Initially, I put the checking code to make sure that the colors were unique but the same duplicate color problem occurs with or without the code check. The next function just returns the unique colors as needed and moves to the next.
I even put a console.log in the code to check and I don't see any duplicate log messages, yet the colors are clearly duplicates.
Using the following function against the colors clearly indicates that the colors are not similar(but in fact duplicate)
// Gets a pixel from the canvas and extracts the color.
onclick(evt) {
var pixelData = this.drawing.context.getImageData(evt.x, evt.y, 1, 1).data;
var hex = "#" + ("000000" + this.rgbToHex(pixelData[0], pixelData[1], pixelData[2])).slice(-6);
console.log(hex);
}
rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
So naturally the question is, what am I missing?
The bug is in the color service. The numbers need to be padded with '0'. If the color is not 6 digits then the color change fails and the previous color is retained and used.
return Math.floor(n).toString(16).padStart(2, '0');
// color service.
#Injectable({provideIn: 'root'})
export class RandomColorService {
colors: string[] = [];
index = 0;
constructor() {
while (this.colors.length < 5000) {
let random = () => {
let n = Math.random() * 256;
return Math.floor(n).toString(16);
}
// make sure there are no duplicate colors.
const color = `#${random()}${random()}${random()}`;
if (!this.colors.includes(color)) {
this.colors.push(color);
}
}
}
public next() {
if (this.index >= 5000) {
this.index = 0;
}
return this.colors[this.index++];
}
}

Processing: How do i create an object every "x" time

What I want to do is to create a new planet in my system for example every 10 seconds and that it starts to move and also prints a "hello" . At the end I want that the 8 planets (ellipses) will be moving together.
I try to use delay(); but I failed .
Can someone help me please?
Planet [] planetCollection = new Planet [8];
float [] wid2 = {100,200,300,400,500,600,700,800};
float [] hig2 = {50,75,100,125,150,175,200,225};
int [] colorR = {100,800,300,400,500,600,700,800};
int [] colorG = {50,225,100,125,150,175,200,225};
int [] colorB = {50,225,100,125,150,175,200,225};
int [] size = {10,12,14,16,18,20,22,24};
int lastTime =0;
int contador =0;
void setup (){
size (1600,1600);
smooth();
//INITIALIZE
for (int i=0 ; i<planetCollection.length; i++){
planetCollection [i] = new Planet(wid2[i], hig2[i], colorR[i],
colorG[i], colorB[i], size[i]);
}
}
void draw (){
background (0);
//CALL FUNCIONALITY
for (int i=0 ; i<planetCollection.length; i++){
planetCollection [i].run();
}
}
class Planet {
//GLOBAL VARIABLES
float val;
float x = 0;
float y = 0;
float wid2;
float hig2;
float speed;
int colorR;
int colorG;
int colorB;
int size;
int centerx = width/2;
int centery = height/4;
//CONTRUCTOR
Planet(float _w, float _h,int _colorR,int _colorG,int _colorB, int _size){
wid2=_w;
hig2=_h;
colorR= _colorR;
colorG= _colorG;
colorB= _colorB;
size = _size;
speed=10/(2*PI * sqrt ((pow(wid2,2)+pow (hig2,2)/2))); ;
}
//FUNCTIONS
void run (){
move();
display();
}
void move (){
x= sin (val);
y= cos(val);
x *=wid2;
y *=hig2;
//SUN/CENTER
noStroke();
fill (255,238,41);
ellipse (centerx,centery,40,40);
if (dist (mouseX,mouseY,centerx,centery)<20){
if(mousePressed){
speed =0;
}
}
//
x+= centerx;
y+= centery;
val += speed;
}
void display (){
//PLanets
fill(colorR, colorG, colorB);
ellipse(x, y, size, size);
///Orbits
noFill();
stroke(255);
ellipse(centerx, centery, wid2*2, hig2*2);
println ("posicionx "+x);
println ("posiciony "+y);
println ("width "+wid2);
println ("high "+hig2);
println ("val "+val);
println ("speed "+speed);
}
}
You can use the modulo % operator along with the frameCount variable inside the draw() function to do something every X frames.
Here is an example program that draws little circles most frames, but draws a big circle every 60 frames:
void setup() {
size(500, 500);
background(0);
}
void draw() {
ellipse(mouseX, mouseY, 10, 10);
if (frameCount % 60 == 0) {
ellipse(mouseX, mouseY, 50, 50);
}
}
You can build a timer for counting seconds using a helper variable and the in-built variable frameRate. (Note that this solution ensures that you truly count seconds independent on your machine's current workload.)
frameRate tells you how many cycles Processing is currently performing per second (one cycle = one execution of draw, also called one frame). This is usually 60 (frames per second) but can also be lower depending on other processes on your machine (e.g. when running video processing, 3D games etc. the frame rate goes down).
Here's a snippet to see what your current frameRate is:
void draw() {
println(frameRate);
}
And here's the timer using a helper variable counter which is reset every second. You should see a new dot appear on the console output every second.
int counter = 0;
void draw() {
if (counter > frameRate) {
print(".");
counter = 0;
} else {
counter++;
}
}
To make it count every 10 seconds you can just change the if condition to "counter > 10 * frameRate".

Spawning random different objects at random locations

I am making a game where there are different objects fall from the upper part of the screen to the lower part of the screen. I am having problems with how can I choose what TextureRegion randomly to be spawned and not to change the already spawned TextureRegions. When I run the game lets say that the electronRegion is spawned first then when the next is spawned and let's say it's an antiprotonRegion the first electronRegion changes to antiprotonRegion that I don't want.
Here is my game class:
public class GameScreenTest implements Screen {
...
#Override
public void render(float delta) {
camera.update();
game.batch.setProjectionMatrix(camera.combined);
game.batch.begin();
game.batch.disableBlending();
game.batch.draw(background, 0, 0);
game.batch.enableBlending();
for(Particles particle: particles) {
particlesControl.draw(particle.x, particle.y);
}
game.batch.end();
if(TimeUtils.millis() - lastDropTime > 500) {
particlesControl.spawn();
particlesControl.update();
}
Iterator<Particles> iter = particles.iterator();
while(iter.hasNext()) {
Particles particle = iter.next();
particle.y -= 200 * Gdx.graphics.getDeltaTime();
if(particle.y + particle.height < 0) {
iter.remove();
}
}
}
...
private class Particles {
private int width;
private int height;
private int x;
private int y;
private Particles() {
}
private void spawn() {
Particles particle = new Particles();
particle.x = MathUtils.random(0, 480 - width);
particle.y = 800;
particle.width = width;
particle.height = height;
particles.add(particle);
lastDropTime = TimeUtils.millis();
}
private void update() {
choice = MathUtils.random(1, 4);
switch(choice) {
case 1:
chosen = new TextureRegion(protonRegion);
width = 75;
height = 75;
break;
case 2:
chosen = new TextureRegion(electronRegion);
width = 75 / 2;
height = 75 / 2;
break;
case 3:
chosen = new TextureRegion(antiprotonRegion);
width = 75;
height = 75;
break;
case 4:
chosen = new TextureRegion(antielectronRegion);
width = 75 / 2;
height = 75 / 2;
break;
}
}
private void draw(int x, int y) {
game.batch.draw(chosen, x, y, width, height);
}
}
I want to know why does all the spawned objects change every time a random choice is taken, and of course, how to solve this problem. Thank You.
Tray this:
public class GameScreenTest implements Screen {
final AntimatterBlast game;
private Texture gameObjects;
private TextureRegion electronRegion;
private TextureRegion antielectronRegion;
private TextureRegion protonRegion;
private TextureRegion antiprotonRegion;
//===========================================//
//remove private TextureRegion chosen;
//===========================================//
private TextureRegion background;
private Music gameMusic;
private OrthographicCamera camera;
private Array<Particles> particles;
private Particles particlesControl;
private long lastDropTime;
private int choice;
public GameScreenTest(final AntimatterBlast game) {
this.game = game;
gameObjects = new Texture(Gdx.files.internal("GameObjects.png"));
electronRegion = new TextureRegion(gameObjects, 105, 103, 50, 50);
antielectronRegion = new TextureRegion(gameObjects, 105, 155, 46, 46);
protonRegion = new TextureRegion(gameObjects, 6, 6, 100, 100);
antiprotonRegion = new TextureRegion(gameObjects, 6, 108, 90, 90);
background = new TextureRegion(gameObjects, 0, 204, 480, 800);
gameMusic = Gdx.audio.newMusic(Gdx.files.internal("DST-ElektroHauz.mp3"));
gameMusic.setLooping(true);
camera = new OrthographicCamera();
camera.setToOrtho(false, 480, 800);
particles = new Array<Particles>();
particlesControl = new Particles();
//===========================================//
//choice = MathUtils.random(1, 4); //remove
//chosen = new TextureRegion(protonRegion); //remove
//===========================================//
}
#Override
public void render(float delta) {
camera.update();
game.batch.setProjectionMatrix(camera.combined);
game.batch.begin();
game.batch.disableBlending();
game.batch.draw(background, 0, 0);
game.batch.enableBlending();
for(Particles particle: particles) {
//===========================================//
particlesControl.draw(particle.chosen, particle.x, particle.y);
//change
//particlesControl.draw(particle.x, particle.y);
//===========================================//
}
game.batch.end();
if(TimeUtils.millis() - lastDropTime > 500) {
//===========================================//
particlesControl.spawn();
//===========================================//
//===========================================//
//remove particlesControl.update();
//===========================================//
}
Iterator<Particles> iter = particles.iterator();
while(iter.hasNext()) {
Particles particle = iter.next();
particle.y -= 200 * Gdx.graphics.getDeltaTime();
if(particle.y + particle.height < 0) {
iter.remove();
}
}
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
gameMusic.play();
particlesControl.spawn();
}
#Override
public void hide() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
gameObjects.dispose();
gameMusic.dispose();
}
private class Particles {
//===========================================//
private TextureRegion chosen; //add variable
//===========================================//
private int width;
private int height;
private int x;
private int y;
private Particles() {
}
private void spawn() {
Particles particle = new Particles();
particle.x = MathUtils.random(0, 480 - width);
particle.y = 800;
particle.width = width;
particle.height = height;
//===========================================//
particle.selectTexture();
//===========================================//
lastDropTime = TimeUtils.millis();
//===========================================//
selectTexture(); //add call
//===========================================//
particles.add(particle);
}
//===========================================//
private void selectTexture() { //change name, but is not nesesari
//===========================================//
choice = MathUtils.random(1, 4);
switch(choice) {
case 1:
//===========================================//
//change
//chosen = new TextureRegion(antielectronRegion);
//if you are not going to change or modific TextureRegion
//independet other the textureRegion,
//I think you could use it well.It is just an idea
chosen = protonRegion;
//===========================================//
width = 75;
height = 75;
break;
case 2:
//===========================================//
//change
//chosen = new TextureRegion(antielectronRegion);
//if you are not going to change or modific TextureRegion
//independet other the textureRegion,
//I think you could use it well.It is just an idea
chosen = electronRegion;
//===========================================//
width = 75 / 2;
height = 75 / 2;
break;
case 3:
//===========================================//
//change
//chosen = new TextureRegion(antielectronRegion);
//if you are not going to change or modific TextureRegion
//independet other the textureRegion,
//I think you could use it well.It is just an idea
chosen = antiprotonRegion;
//===========================================//
width = 75;
height = 75;
break;
case 4:
//===========================================//
//change
//chosen = new TextureRegion(antielectronRegion);
//if you are not going to change or modific TextureRegion
//independet other the textureRegion,
//I think you could use it well.It is just an idea
chosen = antielectronRegion;
//===========================================//
width = 75 / 2;
height = 75 / 2;
break;
}
}
//===========================================//
private void draw(TextureRegion chosen, int x, int y) {
game.batch.draw(chosen, x, y, width, height);
//===========================================//
}
}
}
Like I said in the previous comment the texture (chosen) is in the GameScreenTest and you are using it in the inner class so every single instance of the Particles class will share the same texture.
Not error causing but it might help you to organize the code and make it more readable and by all means you are not obligated to make them just take them as suggestions:
Naming conventions
Naming the class Particles make it seem like the class represents more than 1 Particle, but in fact it represents a single Particle maybe name it only Particle.
Separating the game logic
Make the Particle class deal only with its own problems and don't use it to generate other particles and to add it to an outer class.
Using the constructor since it is already there
Give the Particle the texture that it should use and maybe the coordinates.
Drawing "dead" particle
You are drawing first and asking questions later depending on your game it might feel weird since you will always draw a frame while it no longer exists.
Not really sure on this one
But you might be able to reuse the textures regions instead of a creating a new one of the same texture for every single particle

Java Applet_Dubble Buffering Does Not Work

I'm coding a JApplet in Java, but dubble buffering doesn't remove the flickering!?
What should I do?
This is the important part of the code, I guess (tell me if you need to know more, please):
// Background (dubble buffering)
private Image backbuffer;
private Graphics backg;
//Init method
// Dubble-Buffering
backbuffer = createImage(getWidth(), getHeight());
backg = backbuffer.getGraphics();
backg.setColor(this.getBackground());
//Overrided update method
public void update( Graphics g ) {
g.drawImage( backbuffer, 0, 0, this );
getToolkit().sync();
}
I appreciate all help I can get! :)
I made an MCVE to give you a better insight of the problem (thanks to Andrew Thompson)!
"Main"-class:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.Timer;
public class Test extends JApplet implements ActionListener {
JButton start;
int delay;
Timer tm;
// Falling balls
int n; // Total balls
Ball[] ball; // Array with the balls in
int score;
// The amount of balls falling at the same time (increases by one every
// 10:th score)
int ballNr;
// Comment to the game
String comment;
public void init() {
this.setLayout(null);
this.setSize(600, 500);
this.getContentPane().setBackground(Color.cyan);
this.setFocusable(true);
score = 0;
ballNr = 3;
comment = "Avoid the balls!";
// Buttons
start = new JButton("START");
add(start);
start.setBounds(0, 400, 200, 100);
start.addActionListener(this);
// The timer
delay = 12;
tm = new Timer(delay, this);
// The falling balls
n = 12; // Number of balls in total
ball = new Ball[n];
// Declaring twelve new instances of the ball-object with a
// "reference array"
for (int i = 0; i < n; i++) {
ball[i] = new Ball();
}
}
// Paint-method //
public void paint(Graphics g) {
super.paint(g);
// Every 10:th score, the game adds one ball until you reach 100 =
// win! (ballNr + (int)(score * 0.1) -> ballNr increases by one
// every 10:th score
for (int i = 0; i < ballNr + (int) (score * 0.1); i++) {
// Score can't be higher than 100
if (score < 100) {
g.setColor(ball[i].getCol());
g.fillOval(ball[i].getXLoc(), ball[i].getYLoc(),
ball[i].getSize(), ball[i].getSize());
}
}
// Draw the score and the comment
g.setColor(Color.black);
g.setFont(new Font("Arial", Font.BOLD, 24));
g.drawString("SCORE: " + score, 440, 40);
g.setColor(Color.red);
g.setFont(new Font("Arial", Font.BOLD + Font.ITALIC, 28));
g.drawString(comment, 0, 40);
}
// ACTIONLISTENER //
public void actionPerformed(ActionEvent e) {
if (e.getSource() == start) {
tm.start();
this.requestFocusInWindow(); // Make the runner component have focus
}
// Every 10:th score, the game adds one ball until you reach 100 =
// win! (ballNr + (int)(score * 0.1) -> ballNr increases by one
// every 10:th score
for (int i = 0; i < ballNr + (int) (score * 0.1); i++) {
// Score can't pass 100, because then you have won the game
if (score < 100) {
ball[i].setYLoc(ball[i].getYLoc() + ball[i].getVel());
}
}
// If any ball is out of bounds (then the score increases by one)
for (int i = 0; i < n; i++) {
if (outOfBounds(ball[i])) {
ball[i] = new Ball();
}
}
repaint();
}
// If the ball is out of the screen
public boolean outOfBounds(Ball ball) {
if (ball.getYLoc() >= 500) {
score++;
return true;
} else {
return false;
}
}
// Updates new balls
public void updateBalls() {
for (int i = 0; i < n; i++) {
ball[i] = new Ball();
}
}
}
Sub-class
import java.awt.Color;
import java.util.Random;
public class Ball {
// Private variables
private Random r; // Generating random positions and
// sizes;
private int size; // Size of the ball
private int vel; // Ball velocity
private int nrOfCol; // Color code (see ballColor-method)
private Color col;
private int xLoc;
private int yLoc;
// Constructor
public Ball() {
r = new Random();
size = r.nextInt(40) + 10; // 10px - 50 px
vel = r.nextInt(6) + 1; // Speed btw 1-5 px/delay
nrOfCol = r.nextInt(8) + 1; // Specific nr from 1-9
col = ballColor();
xLoc = r.nextInt(550);
yLoc = 0;}
public Ball(int xPos, int yPos, int size, int vel, Color col) {
this.xLoc = xPos;
this.yLoc = yPos;
this.size = size;
this.vel = vel;
this.col = col;
}
// A method to generate different colors of the balls
public Color ballColor() {
Color col;
switch (nrOfCol) {
case 1:
col = Color.black;
break;
case 2:
col = Color.red;
break;
case 3:
col = Color.green;
break;
case 4:
col = Color.yellow;
break;
case 5:
col = Color.pink;
break;
case 6:
col = Color.magenta;
break;
case 7:
col = Color.white;
break;
case 8:
col = Color.orange;
break;
case 9:
col = Color.blue;
break;
default:
col = Color.black;
// All colors except cyan as it is the background color
}
return col;
}
// Getters & setters
public int getXLoc() {
return xLoc;
}
public int getYLoc() {
return yLoc;
}
public void setYLoc(int y) {
yLoc = y;
}
public int getSize() {
return size;
}
public int getVel() {
return vel;
}
public Color getCol() {
return col;
}
}

show texture on play screen for a little moment

I am making game in libgdx. I want to show tutorials on game start and disappear after few seconds.My code is given below
public class HeroCar{
static final int TUTE_STATE_SHOW = 0;
static final int TUTE_STATE_HIDE = 1;
int tuteState;
float tuteStateTime = 0;
public HeroCar()
{
tuteState = TUTE_STATE_SHOW;
}
public void update(float deltaTime){
if(tuteStateTime >= 0.56f){
tuteStateTime = 0;
tuteState = TUTE_STATE_HIDE;
}
else{
tuteState = TUTE_STATE_SHOW;
}
tuteStateTime += deltaTime;
}
and in game play screen class render method my code is
if(world.heroCar.tuteState == HeroCar.TUTE_STATE_SHOW){
spriteBatch.draw(Assets.speedingup_region, 480 / 2 - 172 / 2, 400, 172, 30);
}
}
Or can can just use Car distance
if(herocar.position.x<50&&canShowTute)
{
fon.draw(batcher,string,posx,posy);
}
else if(herocar.position.x>50&&canShowTute)
{
canShowTute=false;
}
This way u dont have to manage a variable for statetime
Also if car crosses a ceratain distance than manage that no further need to show tute next time.
if(tuteStateTime >= 0.56f){
tuteStateTime = 0; //--------------wrong
tuteState = TUTE_STATE_HIDE;
}
donot set
tuteStateTime = 0
because if you set it 0 then in the next cycle it will check time > 0.56f , then it goes to else block and set state = show...... Hence your tutorial will never dissappear. it will always remain in show state.
If you are saying about alpha of texture then may be this could help.
make
Sprite sprite = new Sprite(Assets.speeding_upregion);
in constuctor. and in render cyle
float step = 0;
float speed = 5;
float alpha = 0;
step = alpha > .9f ? -speed : alpha < .1f ? speed : step; alpha += step * deltaTime;
sprite.draw(spritebatch, alpha);
add your condition before draw if you want to draw or not.