Trying to convert open processing code into pj.5s - java
I have no clue how to change this into p5.js. Just trying to work on conversions. Please help me get this code to work in p5.js.
I know that this is old code and p5.js have different rules. Maybe the array isn't working. I have no clue.
Myself myself;
ArrayList<Enemy> enemies;
`enter code here`ArrayList<Enemy> enemies;
ArrayList<Bullet> myBullets;
ArrayList<Bullet> eneBullets;
void setup(){
size(640, 640);
rectMode(CENTER);
myself = new Myself();
enemies = new ArrayList<Enemy>();
myBullets = new ArrayList<Bullet>();
eneBullets = new ArrayList<Bullet>();
}
void draw(){
background(0);
myself.display();
for(Enemy enemy: enemies){
enemy.display();
}
for(Bullet bullet: myBullets){
bullet.display();
}
for(Bullet bullet: eneBullets){
bullet.display();
}
myself.update();
ArrayList<Enemy> nextEnemies = new ArrayList<Enemy>();
for(Enemy enemy: enemies){
enemy.update();
if(!enemy.isDead){
nextEnemies.add(enemy);
}
}
enemies = nextEnemies;
ArrayList<Bullet> nextMyBullets = new ArrayList<Bullet>();
for(Bullet bullet: myBullets){
bullet.update();
if(!bullet.isDead){
nextMyBullets.add(bullet);
}
}
myBullets = nextMyBullets;
ArrayList<Bullet> nextEneBullets = new ArrayList<Bullet>();
for(Bullet bullet: eneBullets){
bullet.update();
if(!bullet.isDead){
nextEneBullets.add(bullet);
}
}
eneBullets = nextEneBullets;
if(random(1) < 0.02){
enemies.add(new Enemy());
}
}
class Myself{
PVector loc;
float size;
int coolingTime;
boolean isDead;
Myself(){
size = 25;
loc = new PVector(width / 2, height - size / 2 - 10);
coolingTime = 0;
isDead = false;
}
void display(){
if(isDead){
fill(255, 255, 0);
stroke(0, 255, 0);
} else {
noFill();
stroke(0, 255, 0);
}
rect(loc.x, loc.y, size, size);
}
void update(){
isDead = false;
float dmx = mouseX - loc.x;
dmx = constrain(dmx, -5, 5);
loc.x += dmx;
coolingTime++;
if(mousePressed && coolingTime >= 10){
myBullets.add(new Bullet());
coolingTime = 0;
}
for(Bullet b: eneBullets){
if((loc.x - size / 2 <= b.loc.x && b.loc.x <= loc.x + size / 2)
&& (loc.y - size / 2 <= b.loc.y && b.loc.y <= loc.y + size / 2)){
isDead = true;
b.isDead = true;
break;
}
}
for(Enemy e: enemies){
if(abs(loc.x - e.loc.x) < size / 2 + e.size / 2 && abs(loc.y - e.loc.y) < size / 2 + e.size / 2){
isDead = true;
e.isDead = true;
break;
}
}
}
}
class Bullet{
PVector loc;
float vel;
boolean isMine;
boolean isDead;
Bullet(){
loc = new PVector(myself.loc.x, myself.loc.y);
vel = -10;
isMine = true;
}
Bullet(Enemy enemy){
loc = new PVector(enemy.loc.x, enemy.loc.y);
vel = 5;
isMine = false;
}
void display(){
if(isMine){
stroke(0, 255, 0);
} else {
stroke(255, 0, 0);
}
line(loc.x, loc.y, loc.x, loc.y + vel);
}
void update(){
loc.y += vel;
if((vel > 0 && loc.y > height) || (vel < 0 && loc.y < 0)){
isDead = true;
}
}
}
class Enemy{
PVector loc;
float vel;
float size;
int coolingTime;
boolean isDead;
Enemy(){
size = 25;
loc = new PVector(random(size / 2, width - size / 2), -size / 2);
vel = 3;
coolingTime = int(random(60));
isDead = false;
}
void display(){
noFill();
stroke(255, 0, 0);
rect(loc.x, loc.y, size, size);
}
void update(){
loc.y += vel;
if(loc.y > height){
isDead = true;
}
coolingTime++;
if(coolingTime >= 60){
eneBullets.add(new Bullet(this));
coolingTime = 0;
}
for(Bullet b: myBullets){
if((loc.x - size / 2 <= b.loc.x && b.loc.x <= loc.x + size / 2)
&& (loc.y - size / 2 <= b.loc.y && b.loc.y <= loc.y + size / 2)){
isDead = true;
b.isDead = true;
break;
}
}
}
}
If you could just tell me what parts i need to change or fix it it would help me a lot thankyou.
You shouldn't try to translate code line-by-line. Instead, you need to take a step back and understand what the program does, and then you implement that in the target language.
They syntax for Processing (which is based on Java) is very different from the syntax for p5.js (which is based on JavaScript).
Instead of trying to "convert" the code, you need to think in terms of what the code actually does. And then start with a new program in p5.js and do that using p5.js. It's not always going to be a line-by-line conversion.
here's your code:
class myself{
constructor()
{
this.x = 0;
this.y = height-35;
this.size = 25;
this.health = 25;
this.cooldown = 0;
this.plrBullets = [];
}update(){this.cooldown++;
if (mouseIsPressed && this.cooldown>10)
{
this.cooldown = 0;
this.plrBullets.push(new Bullet(true,this.x,this.y));
}
let nextPlrBullets = [];
for (let i = 0; i<this.plrBullets.length; i++)
{
this.plrBullets[i].update();
if (this.plrBullets[i].alive)
{
nextPlrBullets.push(this.plrBullets[i]);
}
}
this.plrBullets = nextPlrBullets;
this.x += constrain(mouseX - this.x, -10, 10);
for (let i = 0; i<eneBullets.length; i++)
{
let c = eneBullets[i];
if (c.x > this.x && c.x < this.x + 25 && c.y > this.y && c.y < this.y + 25)
{
this.health--;
c.alive = false;
if (this.health<=0)
{
print("you lost")
}
}
}
noFill();
stroke(0,255,0);
rect(this.x,this.y,this.size,this.size);
}
}
class enemy{
constructor()
{
this.x = random(15,width-15);
this.y = random(-100,0);
this.size = 25;
this.cooldown = 0;
this.alive = true;
}
update()
{
this.y+=2.5;
this.cooldown++;
if (this.cooldown>20)
{
this.cooldown = 0;
eneBullets.push(new Bullet(false,this.x,this.y));
}
let nextEneBullets = [];
for (let i = 0; i<eneBullets.length; i++)
{
eneBullets[i].update();
if (eneBullets[i].alive)
{
nextEneBullets.push(eneBullets[i]);
}
}
eneBullets = nextEneBullets;
for (let i = 0; i<my_self.plrBullets.length; i++)
{
let c = my_self.plrBullets[i];
if (c.x > this.x && c.x < this.x + 25 && c.y > this.y && c.y < this.y + 25)
{
this.alive = false
c.alive = false;
}
}
if (this.y>height+35)
{
this.y = random(-100,0);
}
noFill();
stroke(255,0,0);
rect(this.x,this.y,this.size,this.size);
}
}
class Bullet{
constructor(dir,x,y)
{
this.x = x;
this.speed = 5;
this.dir = dir;
this.alive = true;
this.y = y;
}
update()
{
if (this.dir)
{
this.y -= this.speed;
}else{
this.y += this.speed;
}
if (this.y<-20)
{
this.alive = false;
}//this.y = -25;
if(this.dir)
{
stroke(0,255,0);
}else{
stroke(255,0,0);
}
line(this.x,this.y,this.x,this.y+25);
}
}
let my_self;
let eneBullets = [];
let enemies = [];
function setup()
{
createCanvas(640,640);
rectMode(CENTER);
my_self = new myself();
for (let i = 0; i<10; i++)
{
enemies.push(new enemy());
}
}
function draw()
{
background(0);
if(random(1) < 0.02 && enemies.length<15){
enemies.push(new enemy());
}
my_self.update();
let newEnimies = [];
for (let i = 0; i<enemies.length; i++)
{
enemies[i].update();
if (enemies[i].alive)
{
newEnimies.push(enemies[i]);
}
s}
enemies = newEnimies;
if (enemies.length == 0)
{
print("you win");
}
}
Sorry that the collisions are a bit wacky but when converting processing to p5 here are some tips:
1: don’t use array lists use arrays with push instead of add
2: no data types only LET
3: print not println
4: class constructors are declared as “constructor” instead of class name
5: use “function” before function declaration instead of void
6: pvector is vector
7: google is your friend
8: the p5 documentation
Related
Java: Super class won't override function
I have been working on a game for a while and I would like to have a different class for each type of Creature that there is. Right now, all of the different creatures' AI is run in a long switch and I would like a superclass to ovveride that function with that AI for that creature. I have this set up but it won't override. Am I forgetting something? Bunny.java: package creature; import org.newdawn.slick.opengl.Texture; import creature.Creature; import creature.CreatureType; import data.Tile; public class Bunny extends Creature{ public Bunny(CreatureType type, float x, float y, float speed1) { super(type, x, y, speed1); } public void AI(int type) { System.out.println("test"); } } Creature.java: public Creature(CreatureType type, float x, float y, float speed1) { this.texture = drawImg(type.textureName); this.textureHamster = drawImg("creatures/HamsterFace"); this.healthBackground = drawImg("health_background"); this.healthForeground = drawImg("health_foreground"); this.healthBorder = drawImg("health_border"); this.startTile = startTile; this.x = x; this.y = y; this.intX = (int) x; this.intY = (int) y; this.width = texture.getImageWidth(); this.height = texture.getImageHeight(); this.speed1 = speed1; this.speed = speed; this.intspeed = speed; this.grid = grid; this.health = type.health; this.inithealth = type.health; this.hiddenHealth = health; this.startHealth = health; this.dir = false; this.dchosen = false; this.setx = 0; this.hurt = 0; this.panick = 0; this.deathWish = 0; this.pdir = -1; this.myX = x; this.myY = HEIGHT / 2; this.right = false; this.left = false; this.fade = 0; this.fir = true; this.aiType = type.aiType; this.yOffset = 0; } ..... public void AI(int type) { if(panic > 0) panic--; hurt(); speed = speed1; switch(type) { case 1: if(panic > 0) { if(pickRandom(150, 300) < 10) { direction = !direction; } if(direction) { if(!right) { x += speed; } else { if(falling < 2) gravity = 8; } } else { if(!left) { x -= speed; } else { if(falling < 2) gravity = 8; } } } else { if(getRange(WIDTH / 2, myX) > 200) { directionCoolDown++; if(directionCoolDown > pickRandom(150, 3000)) { direction = !direction; directionCoolDown = 0; } if(direction) { if(!right) { x += speed / 3.2; } else { if(falling < 2) gravity = 8; } } else { if(!left) { x -= speed / 3.2; } else { if(falling < 2) gravity = 8; } } } else { if(myX < WIDTH / 2) { direction = true; } else { direction = false; } } } break; case 2: yOffset = -25; if(!angry) { pdir = 0; if(getRange(Player.getX(), myX) < 300) { hamsterFace = true; } else { hamsterFace = false; } if(!hamsterFace) { directionCoolDown++; if(directionCoolDown > pickRandom(150, 3000)) { direction = !direction; directionCoolDown = 0; } if(direction) { if(!right) { x += speed / 3.2; } else { if(falling < 2) gravity = 8; } } else { if(!left) { x -= speed / 3.2; } else { if(falling < 2) gravity = 8; } } } } else { pdir++; hamsterFace = false; if(myX < Player.getX()) { direction = true; } else { direction = false; } if(direction) { if(!right) { x += speed / 1; } else { if(falling < 2) gravity = 8; } } else { if(!left) { x -= speed / 1; } else { if(falling < 2) gravity = 8; } } if(getRange(myX, Player.getX()) < 5 && getRange(myY, Player.getY()) < 5) { hurtPlayer(-2); direction = !direction; if(direction) { if(!right) { x += speed * 10; } else { if(falling < 2) gravity = 8; } } else { if(!left) { x -= speed * 10; } else { if(falling < 2) gravity = 8; } } } } if(panic > 1) { angry = true; } else { if(pdir > pickRandom(1000,2000)) { angry = false; } } break; } } ..... (Both classes are in the same package) EDIT: I fixed the typo....
you have in the Bunny class: public void AI() { System.out.println("test"); } in the Creature class: public void AI(int type) { if(panic > 0) .... so void AI(int type) and void AI() are NOT the same method (check the signature and how they take different parameters!) therefore the Bunny class is not overriding anything from the parent class -- edit: now that your classes have a method void AI(int type) then we can say that Bunny override the Creature AI method and everytime you call bunny.AI(f) your bunny method will be called!
How do i make an array of bouncing objects that bounce off of each other?
I'm new to programming and I need to make ten or more bouncing objects that will bounce off of each other. Can someone give me an example of a program that will create this? Edit:Here is the code that I'm currently working on. //main program float hue; float alpha; float scale = 50; AnArray HmWd; void setup(){ size(1000,1000); colorMode(HSB, 360, 100, 100); HmWd = new AnArray(scale,3); } void display(){ background(0,0,100); HmWd.display(); } AnArray class: class AnArray{ Agent Gems1[]; Agent Gems2[]; Agent Gems3[]; Agent Gems4[]; Agent Gems5[]; float size; int quant; int ol = 1; AnArray(float _size,int _quant){ size = _size; quant = _quant; for(int i=0; i<quant;i++){ Gems1[i]=new Agent(size,ol); //I'm getting a "NullPointerException" Error here ol++; Gems2[i]=new Agent(size,ol); ol++; Gems3[i]=new Agent(size,ol); ol++; Gems4[i]=new Agent(size,ol); ol++; Gems5[i]=new Agent(size,ol); ol=1; } } void display(){ for(int i=0; i<quant;i++){ Gems1[i].display(); Gems2[i].display(); Gems3[i].display(); Gems4[i].display(); Gems5[i].display(); } } } Agent class: class Agent{ PVector position, speed; float r; float highlightHue, basicHue; Agent(float _r,int c){ position = new PVector((random(100,900)),(random(100,900))); r = _r; ///radius is for test intersection speed = new PVector(2,2); highlightHue = 72+(5*c); basicHue = 190+(5*c); hue = basicHue; } PVector getCenter(){ PVector center = new PVector(); center.x = position.x ; center.y = position.y ; return center; } void highlight(){ hue = highlightHue; } void reverseSpeed(){ speed.x *= -1; } void display(){ colorMode(HSB); fill(hue, 200,200,alpha); stroke(50, alpha); ellipse(position.x,position.y, 2*r,2*r); hue= basicHue; } void move(){ if( position.x >width || position.x < 0){ speed.x *= -1; } if( position.y > height || position.y < 0){ speed.y *= -1; } position.add(speed); } void grow(){ if( r < 150){ r++; alpha = alpha > 50? alpha -= 2: 50; //ternary assignment operator } } void shrink(){ if( r>10){ r--; alpha = alpha< 200? alpha +=2: 200; } } boolean intersect( Agent a){ boolean isIntersect = false; float d = PVector.dist(position,a.position); if(d < this.r + a.r){ isIntersect= true; } return isIntersect; } }
Transition 2D player Position A to B on JAVA
Am having issues trying to figure out how to translate or 'animate' my player's position to a new tile, this is what am doing : if (input.right){ x += 1; Right now am listening for key.inputs and then x++/x-- or y++/y-- on my players position that makes him move pixel by pixel, but i want my player to move exactly to the next tile(32 pixels) with one hit of the key with like a linear transition from the player's tile position to the next tile over time? Something like (pseudo code i think..) if input && walking false walking = true increment 1 by 1 32 ints to X over time? after completed walking = false I still cant even figure out the logic behind something like that. An example is the movement in a game called Tibia. Now Some bits of my code (player related).. GAMECLASS > public Game() player = new Player(playerSpawn.x(), playerSpawn.y(), key); player.init(level); public void run() .... render(); frames++; .... public void update() key.update(); player.update(); level.update(); public void render() ..... int xScroll = ( player.x + 32) - screen.width / 2; int yScroll = ( player.y + 32) - screen.height / 2; level.render(xScroll, yScroll, screen); player.render(screen); for (int i =0; i < pixels.length; i++){ pixels[i] = screen.pixels[i]; } SCREENCLASS > ...... public int[] pixels; public int[] tiles = new int[VIEW_SIZE * VIEW_SIZE]; ..... public void renderTile(int xp, int yp, Tile tile){ xp -= xOffset; yp -= yOffset; for (int y = 0; y < tile.sprite.SIZE; y++){ int ya = y + yp; for (int x = 0; x < tile.sprite.SIZE; x++){ int xa = x + xp; if (xa < -tile.sprite.SIZE || xa >= width || ya < 0 || ya >= height) break; if (xa < 0) xa = 0; pixels[xa + ya * width] = tile.sprite.pixels[x + y * tile.sprite.SIZE]; } } } //THIS IS THE METHOD CALLED TO RENDER THE PLAYER > SEE BELLOW AT THE PLAYER CLASS FOR THE CALL public void renderMob(int xp, int yp, Mob mob){ xp -= xOffset; yp -= yOffset; for (int y = 0; y < 64; y++){ int ya = y + yp; int ys = y; for (int x = 0; x < 64; x++){ int xa = x + xp; int xs = x; if (xa < -64 || xa >= width || ya < 0 || ya >= height) break; if (xa < 0) xa = 0; int col = mob.getSprite().pixels[xs + ys * 64]; if (mob instanceof Chazer && col == 0xFF9b0000) col = 0xff54ff00; if (col != 0xFFFF00FF) pixels[xa + ya * width] = col; } } } PLAYERCLASS > public Player(int x , int y, Keyboard input){ this.x = x; this.y = y; this.input = input; } //PLAYER UPDATE public void update(){ if (anim < 7500) anim++; else anim = 0; if (input.down) ya = 1; if (input.up) ya = -1; if (input.left) xa = -1; if (input.right) xa = 1; //CHECK BELLOW TO THIS MOVE METHOD if (xa != 0){ move(xa, 0); } else if(ya != 0){ move(0, ya); } } clear(); } //HERE ANIMATION AND CHOOSE WHAT SPRITE = WHERE PLAYER IS LOOKING AT public void render(Screen screen){ if (dir == 0) { sprite = Sprite.player_n; if (walking) { if (anim % 20 > 10){ sprite = sprite.player_n1; } else { sprite = sprite.player_n2; } } } if (dir == 1) { sprite = Sprite.player_e; if (walking) { if (anim % 20 > 10){ sprite = sprite.player_e1; } else { sprite = sprite.player_e2; } } } if (dir == 2) { sprite = Sprite.player_s; if (walking) { if (anim % 20 > 10){ sprite = sprite.player_s1; } else { sprite = sprite.player_s2; } } } if (dir == 3) { sprite = Sprite.player_w; if (walking) { if (anim % 20 > 10){ sprite = sprite.player_w1; } else { sprite = sprite.player_w2; } } } // ADDING OFFSET CUZ THE PLAYER IS DOUBLE THE SIZE OF THE TILE int xx = x - 42; int yy = y - 42; screen.renderMob(xx, yy, sprite); } //THIS IS HOW I MOVE THE PLAYER public void move(int xa, int ya){ if (xa != 0 && ya != 0){ move(xa, 0); move(0, ya); return; } if (xa > 0) dir = 1; if (xa < 0) dir = 3; if (ya > 0) dir = 2; if (ya < 0) dir = 0; if(!collision(xa, 0)){ x += xa; } if(!collision(0, ya)){ y += ya; } } Thanks alooot! **Run method! public void run() { long xlastTime = System.nanoTime(); long timer = System.currentTimeMillis(); final double xns = 1000000000.0 / 60.0; double delta = 0; int frames = 0; requestFocus(); while(running){ long xnow = System.nanoTime(); delta += (xnow-xlastTime) / xns; xlastTime = xnow; while (delta >= 1) { update(); delta--; } render(); frames++; if (System.currentTimeMillis() - timer > 1000){ timer += 1000; frame.setTitle(title + " | " + frames + " fps"); frames = 0; } } stop(); }
What I would do is declare two int fields in the player class: private float xToMove = 0; private float yToMove = 0; Then, under your input event: if (input.down && yToMove == 0) yToMove = -32; if (input.up && yToMove == 0) yToMove = 32; if (input.left && xToMove == 0) xToMove = -32; if (input.right && xToMove == 0) xToMove = 32; And finally, in your Player class's update method: public void update() { if (xToMove > 0) { xToMove--; x++; } if (xToMove < 0) { xToMove++; x--; } if (yToMove > 0) { yToMove--; y++; } if (yToMove < 0) { yToMove++; y--; } } Of course this is simplified a bit but the concept is there EDIT: to change the speed. Note that xToMove and yToMove have been changed to floats. You can use a float to represent the amount of time 1 move takes float period = 1000; //The time one move takes in milliseconds Somewhere you should calculate the number of pixels to be moved each frame. You could make a calculateSpeed() method or just throw it into the constructor or something. Depends on if you want speed to change during the game. float speed = 32f / (fps * (period / 1000f)); //fps should be obtained dynamically and should be a float Then when you update you should do this: if (xToMove > 0) { xToMove -= speed; x += speed; if (xToMove <= 0) { //Set these guys to nice even numbers to prevent problems xToMove = 0; x = (float) Math.round(x); } } Also make sure that x and y are floats. EDIT 2: fps int frames = 0; int fps = 60; requestFocus(); while(running){ long xnow = System.nanoTime(); delta += (xnow-xlastTime) / xns; xlastTime = xnow; while (delta >= 1) { update(); delta--; } render(); frames++; if (System.currentTimeMillis() - timer > 1000){ timer += 1000; fps = frames; frame.setTitle(title + " | " + fps + " fps"); frames = 0; } } stop();
Restarting millis in processing error
Having a massive problem with this piece of code. I'm working with Java in processing. I've created a game where users must guide a character away from objects. All the objects, health system and score system are based on mills(). Once the game ends we need to reset millis(), resetting the objects, score and health system. I have searched implemented advice from friends and previously asked questions on here but the advice differs very slightly. I'm assuming it's something that I can't see. I would really appreciate your help with this, I only ever use this site as a last resort not just when I'm feeling lazy. //these are used to set the times which the games increases difficulty //int timeDelay = 30000; int delayOne = 2000; int delayTwo = 5000; int delayThree = 80000; int delayFour = 90000; int display = 2000; //for collisions float[] xpos = new float[6]; float[] ypos = new float[6]; //timer counts how many millis() each game lasts for int timeStamp = 5000; int timer; int timer2 = millis() - timer; //always at zero //outputting score at the end of a game int score; int start; //trying to get lives working boolean lost = false; //variable to store & output gale force when giving score int Gale = 0; //Changing length rectangle float rX = 350.0; float x1 = 20; float y1 = 20; float w1 = 100; float h1 = 30; //DECLARE OBJECTS JELLY CLASS Jelly myObject; Jelly myObject1; Jelly myObject2; Jelly myObject3; //GENTLEMAN CLASS gentleMan mygentleMan; //LOLLY CLASS Lolly myCow; Lolly myCow1; //PImages PImage loader; PImage bg; PImage uh; PImage bg1; PImage bolt; PImage over; void setup() { bg=loadImage("backy1.png"); bg1 = loadImage("backy.png"); over = loadImage("over.png"); PFont L = loadFont("Lobster1.3-48.vlw"); textFont( L, 16); size(400, 600); smooth(); //begin = millis(); imageMode(CENTER); //INITIALISE myObject = new Jelly(320, 500); myObject1 = new Jelly(150, 200); // myObject2 = new Jelly(550, 500); //myObject3 = new Jelly(300, 100); mygentleMan = new gentleMan(200, 300); //myObject.run(); //myObject1.run(); //myObject2.run(); myCow = new Lolly(400, 250); myCow1 = new Lolly(150, 350); timer = millis(); } void draw() { start = 0; //because we have image mode set to center for collisions //we have to divide the height & width of the screen by 2 for hte image to fit image(bg, 200, 300); if (millis() >= start + delayOne) { image(bg1, 200, 300); } //CALL FUNCTIONALITY myObject.run(); myObject.put_in_array(0); myObject1.run(); // this one is going top to bottom myObject1.put_in_array(1); // myObject2.run(); //myObject2.put_in_array(2); // myObject3.run(); //myObject3.put_in_array(3); myCow.run(); myCow.put_in_array(4); myCow1.run(); myCow1.put_in_array(5); mygentleMan.run(); //health bar fill(161, 221, 16); noStroke(); rect(10, 24, rX, 10); if(rX <= 100) { fill(221, 59, 16); rect(10, 24, rX, 10); } else if(rX <= 200) { fill(221, 137, 16); rect(10, 24, rX, 10); } if(rX == 5.0) { lost = true; noLoop(); // lives = lives - 1; image(over, width/2, height/3); fill(255); text("Your Score Is: " + timer, width/2.7, height/2); text("Gale Force Is; " + Gale, width/2.7, height/1.8); score = timer; } //For Loop detecting collisions between mygentleMan & objects for (int i=0; i < 6; i++) { if (xpos[i] > 150 && xpos[i] < 250 && ypos[i] > (mygentleMan.y-58) && ypos[i] < (mygentleMan.y+58)) { // text("collision", 200, 300); bolt = loadImage("bolt.png"); image(bolt, xpos[i], ypos[i]); rX = rX - 1; } //outputting score on screen # at all times fill(255); text("Score: " + timer, 320, 20); } //timer which will be score counter essentially timer = millis(); //text(timer, 20, 20); //moving the man up the screen if button is pressed, if not he levitates downward if (keyPressed) { mygentleMan.y -= mygentleMan.moveY; mygentleMan.moveY += 0.4; } else { mygentleMan.y += mygentleMan.moveY; mygentleMan.moveY += 0.2; } fill(255); text("Health", 20, 20); if(mousePressed) { if(timer2 > timeStamp) { println("tit"); mygentleMan.y = height/2; loop(); } } } //class for first objects that move into the screen class Jelly { //GLOBAL VARIABLES float x = 0; float y = 0; float speedX = 1.8; float speedY = 1.8; float speedX2 = 2.1; float speedY2 = 2.1; float speedX3 = 2.2; float speedY3 = 2.2; PImage jelly = loadImage("jelly.png"); PImage hat = loadImage("hat.png"); PImage gale = loadImage("g1.png"); PImage force = loadImage("force.png"); PImage news = loadImage("news.png"); //CONSTRUCTOR Jelly(float _x, float _y) { x = _x; y = _y; } //FUNCTIONS void run() { display(); move(); bounce(); image(force, 330, 550); if (millis() >= start + delayOne) { display(); moveFast(); bounceFast(); image(gale, 280, 560); Gale = 1; if (start + delayOne + display >= millis()) { image(news, 200, 300); } } if (millis() >= start +delayTwo) { display(); moveFaster(); bounceFaster(); image(gale, 310, 560); Gale = 2; if (start + delayTwo + display >= millis()) { image(news, 200, 300); } } } void bounce() { if ( x > width) { speedX = speedX * -1; //multiply by -1 to make it bounce } if ( x < 0) { speedX = speedX * -1; } if ( y > height) { speedY = speedY * -1; } if ( y < 0) { speedY = speedY * -1; } } void bounceFast() { if ( x > width) { speedX2 = speedX2 * -1; //multiply by -1 to make it bounce } if ( x < 0) { speedX2 = speedX2 * -1; } if ( y > height) { speedY2 = speedY2 * -1; } if ( y < 0) { speedY2 = speedY2 * -1; } } void bounceFaster() { if ( x > width) { speedX3 = speedX3 * -1; //multiply by -1 to make it bounce } if ( x < 0) { speedX3 = speedX3 * -1; } if ( y > height) { speedY3 = speedY3 * -1; } if ( y < 0) { speedY3 = speedY3 * -1; } } void move() { x = x + speedX; y = y + speedY; } void moveFast() { x = x + speedX2; y = y + speedY2; } void moveFaster() { x = x + speedX3; y = y + speedY3; } void put_in_array(int a) { xpos[a] = x; ypos[a] = y; } void display() { image(hat, x, y); } } //class for gentleman that floats class gentleMan { //GLOBAL VARIABLES float y = 400; float x = 400; float moveY; //PImage umbrella; PImage umbrella = loadImage("dafuq.png"); PImage over = loadImage("over.png"); //CONSTRCUTOR --- PIECES OF INFO PROVDE TO BUILD CLASS -- INTIIALIZE VARIBALE gentleMan(float _x, float _y) { y = _y; x = _x; moveY = 2; } //FUNCTIONS void run() { display(); keyReleased(); bounce(); // collision(); } void display() { image(umbrella, x, y); } void keyReleased() { mygentleMan.moveY = 4; } void bounce() { if ( y < 0) { y = 0; } if (y > height) { //score = millis(); lost = true; noLoop(); // lives = lives - 1; image(over, width/2, height/3); text("Your Score Is: " + timer, width/2.7, height/2); text("Gale Force Is; " + Gale, width/2.7, height/1.8); } } } class Lolly { //GLOBAL VARIABLES float x = 0; float y = 0; float speedX = 2; float speedY = 2; float speedX1 = 2.1; float speedY1 = 2.1; float speedX2 = 2.3; float speedY2 = 2.3; PImage cow = loadImage("cow.png"); //CONSTRUCTOR Lolly(float _x, float _y) { x = _x; y = _y; } //FUNCTIONS void run() { // display(); //move(); //bounce(); if (millis() >= start + delayThree) { display(); moveFast(); bounceFast(); } if (millis() >= start +delayFour) { display(); moveFaster(); bounceFaster(); } } void put_in_array(int a) { xpos[a] = x; ypos[a] = y; } void bounce() { if ( x > width) { speedX = speedX * -1; //multiply by -1 to make it bounce } if ( x < 0) { speedX = speedX * -1; } if ( y > height) { speedY = speedY * -1; } if ( y < 0) { speedY = speedY * -1; } } void bounceFast() { if ( x > width) { speedX1 = speedX1 * -1; //multiply by -1 to make it bounce } if ( x < 0) { speedX1 = speedX1 * -1; } if ( y > height) { speedY1 = speedY1 * -1; } if ( y < 0) { speedY1 = speedY1 * -1; } } void bounceFaster() { if ( x > width) { speedX2 = speedX2 * -1; //multiply by -1 to make it bounce } if ( x < 0) { speedX2 = speedX2 * -1; } if ( y > height) { speedY2 = speedY2 * -1; } if ( y < 0) { speedY2 = speedY2 * -1; } } void move() { x = x + speedX; y = y + speedY; } void moveFast() { x = x + speedX1; y = y + speedY1; } void moveFaster() { x = x + speedX2; y = y + speedY2; } void display() { image(cow, x, y); } }//end of cow class void mousePressed() { }
Your question is not at all clear, but it sounds like you should be able to wrap System.currentTimeMillis() in an object that maintains a starting point and returns the offset. Something like public class Millis { long start; public Millis() { this.reset(); } public void reset() { this.start = System.currentTimeMillis(); } public long getMillis() { return System.currentTimeMillis() - start; } } You create an instance of this class at startup Millis timer = new Millis(); then call reset() to set it back to zero at the beginning of each game. Everywhere in your code you currently have millis() you would have timer.getMillis()
Use a custom timer class class Timer { int savedTime; // When Timer started int totalTime; // How long Timer should last Timer(int tempTotalTime) { totalTime = tempTotalTime; } // Starting the timer void start() { // When the timer starts it stores the current time in milliseconds. savedTime = millis(); } // The function isFinished() returns true if 5,000 ms have passed. // The work of the timer is farmed out to this method. boolean isFinished() { // Check how much time has passed int passedTime = millis()- savedTime; if (passedTime > totalTime) { return true; } else { return false; } } }//end class Then to call firstTimer = new Timer(50000); And then in the draw to check if (firstTimer.isFinished()) { //do sopemthing //then restart timer firstTimer.start(); } else { // do soemthing else for the rest of the time.... }
Triangles with texture in processing
I have a code in processing which contains points moving randomly. Those points seek the ball and start triangulate (shaping triangles). I want to display on them a folder of sequences images with opacity. So every time that an triangle is shaped will be textured with an image. I have tried to use texture and loadimage function but it seems that the problem is that triangles is rendered rapidly with various points and texture can not be seen properly. import processing.opengl.*; float r1, r2; void setup() { size(800, 800, OPENGL); for (int j=0; j<numAgents; j++) agents[j]=new agent(); for (int i=0; i<numMovers; i++) movers[i]=new Mover(); smooth(); } void draw() { background(0); for (int i=0; i<numMovers; i++) { movers[i].update(); movers[i].checkEdges(); movers[i].display(); int closestAgentNumber=-1; for (int j=0; j<numAgents; j++) { agents[j].checkEdges(); agents[j].display(); agents[j].update(); agents[j].repel(); float d = dist(agents[j].location.x, agents[j].location.y, movers[i].location.x, movers[i].location.y ); if (d < 100) { closestAgentNumber=j; } if (d<200) { agents[j].behaviour=1; agents[j].follow(movers[i].location.x, movers[i].location.y); movers[i].hit = true; } else if (d>100) { movers[i].hit = false; agents[j].behaviour=0; } } } } int numAgents= 100; agent[]agents =new agent[numAgents]; class agent { PVector location; PVector velocity; PVector acceleration; float topspeed; float r1, r2; // boolean connect=false; int behaviour; boolean follow=false; //boolean follow= false; agent() { float speed=800; if (behaviour==0) { location= new PVector(random(0, speed), random(0, speed)); velocity= new PVector(1, 1); acceleration= new PVector( random(-0.01, 0.01), random(-0.01, 0.01)); acceleration.normalize(); topspeed=5; } else if (behaviour==1) { // connect=true; } // Set to acceleration } void follow(float x, float y) { if (follow==true) { // follow==true; // Our algorithm for calculating acceleration: PVector moverPos = new PVector(x, y); PVector dir = PVector.sub(moverPos, location); // Find vector pointing towards mouse dir.normalize(); // Normalize dir.mult(4); // Scale acceleration = dir; } } void update() { velocity.add(acceleration); velocity.limit(topspeed); location.add(velocity); } void display() { pushMatrix(); translate(location.x, location.y); if (behaviour==1) { fill(255, 0, 0); } else if ( behaviour==0) { fill(255, 255, 255); } ellipse(0, 0, 4, 4); strokeWeight(1); popMatrix(); } void checkEdges() { if (location.x < 0) { location.x = 0; velocity.x *= -1; acceleration.mult(0.001); } if (location.x > 800) { location.x = 800; velocity.x *= -1; acceleration.mult(0.001); } if (location.y < 0) { location.y = 0; velocity.y *= -1; acceleration.mult(0.001); } if (location.y > 800) { location.y = 800; velocity.y *= -1; acceleration.mult(0.001); } } void repel() { for (int i=0; i<numAgents; i++) { if ((agents[i].behaviour==1)) { int k; k=1; for (int j=0; j<numAgents; j++) { //-------------- // float dm = agents[i].location.dist(agents[k].location); float dm = dist(agents[j].location.x, agents[j].location.y, agents[i].location.x, agents[i].location.y); if (dm < 50) { agents[i].velocity.mult(-1); agents[i].acceleration.mult(0.5); agents[j].velocity.mult(-1); agents[j].acceleration.mult(0.5); } else if (behaviour==0) { agents[i].velocity.mult(1); agents[j].velocity.mult(1); } //float dm = dist(agents[i].location.x, agents[i].location.y, agents[j].location.x, agents[j].location.y); // float dm = agents[i].location.dist(agents[j].location); // int clr=(int) map (dm,0,100,200,0); if (dm<180 && dm>100) { if ( k<2) { //println(dm); //stroke(255,0,0); r1 = agents[j].location.x; r2 = agents[j].location.y; k=k+1; } else { //fill(random(255),random(255),random(255),random(0,20)); //stroke(0,50); // texture(A); //fill(random(0,255),random(0,255),random(0,255),random(0, 40)); // stroke(140, 50); fill(random(0, 255), random(0, 255), random(0, 255), random(0, 10)); stroke(140, 50); beginShape(); //texture(); // image(A,agents[i].location.x, agents[i].location.y); vertex(agents[i].location.x, agents[i].location.y); vertex(r1, r2); vertex(agents[j].location.x, agents[j].location.y); endShape(CLOSE); j=300; } } } /*void triangulate() { fill(random(0, 255), random(0, 255), random(0, 255), random(0, 40)); stroke(140, 50); for (int i=0; i<numAgents; i++) { //gens[i].connect==true) //if(! agents[i].connect) if (agents[i].behaviour==1) { //println(agents[i]); int k; k=1; for (int j=0; j<numAgents; j++) { float dm = dist(agents[i].location.x, agents[i].location.y, agents[j].location.x, agents[j].location.y); // float dm = agents[i].location.dist(agents[j].location); // int clr=(int) map (dm,0,100,200,0); if (dm<180 && dm>100) { if ( k<2) { //println(dm); //stroke(255,0,0); } } } }*/ } } } } int numMovers= 1; Mover[]movers= new Mover[numMovers]; class Mover { PVector location; PVector velocity; PVector acceleration; float topspeed; boolean hit = false; Mover() { float spead = 800; location = new PVector(random(0,spead),random(0,spead)); velocity = new PVector(0,0); acceleration = new PVector(random(-1,1),random(-1,1));//random initial acceleration topspeed = 4; } void update() { // Motion 101! Velocity changes by acceleration. Location changes by velocity. velocity.add(acceleration); velocity.limit(topspeed); location.add(velocity); } void display() { pushMatrix(); translate(location.x,location.y); //fill(102,0,155,random(120,160)); //fill(32,225,245,127 + sin(frameCount*.01) * 127); if(hit) fill(255,10,96,120); else fill(3,225,190,random(50,127)); ellipse(0,0,30,30); noStroke(); popMatrix(); } void checkEdges() { if(location.x < 0){ location.x = 0; velocity.x *= -1; acceleration.mult(0.001); } if(location.x > 800){ location.x = 800; velocity.x *= -1; acceleration.mult(0.001); } if(location.y < 0){ location.y = 0; velocity.y *=- 1; acceleration.mult(0.001); } if(location.y > 800){ location.y = 800; velocity.y *= -1; acceleration.mult(0.001); } } }
You will need to use 3 Processing functions for this: tint() - which you'll use for transparency (e.g. tint(255,127); will make the image/texture 50% transparent (127 of 255) ) texture() - this sets texture to a shape(beginShape(),endShape() block). You pass call it after beginShape() and then you pass two additional arguments when calling vertex(), which are your texture coordinates textureMode() - If you always know the size of your texture image, this is optional, but it's handy to know about this. By default the texture mode is set to IMAGE meaning that for a 100x100 px image that you will map to a 300 units long quad for example, you will map the vertex corner positions with the texture coordinates as in the example bellow. default texture mode (textureMode(IMAGE)) //assumes tex is already initialized/loaded PImage beginShape(); texture(tex); vertex(-150,-150,0, 0, 0);//top-left vertex( 150,-150,0, 100, 0);//top-right vertex( 150, 150,0, 100,100);//bottom-right vertex(-150, 150,0, 0,100);//bottom-left endShape(); The other option is to use NORMALIZED mode, which instead of actual pixel values, takes normalized values (between 0.0 and 1.0), so the above example in NORMALIZED mode is: beginShape(); texture(tex); vertex(-150,-150,0, 0.0,0.0);//top-left vertex( 150,-150,0, 1.0,0.0);//top-right vertex( 150, 150,0, 1.0,1.0);//bottom-right vertex(-150, 150,0, 0.0,1.0);//bottom-left endShape(); textureMode() is called usually once in setup() and the advantage is you won't have to worry about knowing all the dimensions of all your textures, especially when you use more than one texture in your sketch. So, back to your code, you need to initialize the texture like so: tex = loadImage("yourTextureImage.png"); textureMode(NORMALIZED); and later in repel() function when you draw your shape, you would do this: beginShape(); tint(255,127); texture(tex); vertex(agents[i].location.x, agents[i].location.y,0.0,0.0);//aditional u,v coordinates 0,0 - top left of texture vertex(r1, r2,1.0,0.0);//top right texture coordinate vertex(agents[j].location.x, agents[j].location.y,1.0,1.0);//bottom right texture coordinat endShape(CLOSE); So the full code would look like this: import processing.opengl.*; float r1, r2; PImage tex; void setup() { size(800, 800, OPENGL); for (int j=0; j<numAgents; j++) agents[j]=new agent(); for (int i=0; i<numMovers; i++) movers[i]=new Mover(); tex = loadImage("yourImage.png"); textureMode(NORMALIZED); smooth(); } void draw() { background(0); for (int i=0; i<numMovers; i++) { movers[i].update(); movers[i].checkEdges(); movers[i].display(); int closestAgentNumber=-1; for (int j=0; j<numAgents; j++) { agents[j].checkEdges(); agents[j].display(); agents[j].update(); agents[j].repel(); float d = dist(agents[j].location.x, agents[j].location.y, movers[i].location.x, movers[i].location.y ); if (d < 100) { closestAgentNumber=j; } if (d<200) { agents[j].behaviour=1; agents[j].follow(movers[i].location.x, movers[i].location.y); movers[i].hit = true; } else if (d>100) { movers[i].hit = false; agents[j].behaviour=0; } } } } int numAgents= 100; agent[]agents =new agent[numAgents]; class agent { PVector location; PVector velocity; PVector acceleration; float topspeed; float r1, r2; // boolean connect=false; int behaviour; boolean follow=false; //boolean follow= false; agent() { float speed=800; if (behaviour==0) { location= new PVector(random(0, speed), random(0, speed)); velocity= new PVector(1, 1); acceleration= new PVector( random(-0.01, 0.01), random(-0.01, 0.01)); acceleration.normalize(); topspeed=5; } else if (behaviour==1) { // connect=true; } // Set to acceleration } void follow(float x, float y) { if (follow==true) { // follow==true; // Our algorithm for calculating acceleration: PVector moverPos = new PVector(x, y); PVector dir = PVector.sub(moverPos, location); // Find vector pointing towards mouse dir.normalize(); // Normalize dir.mult(4); // Scale acceleration = dir; } } void update() { velocity.add(acceleration); velocity.limit(topspeed); location.add(velocity); } void display() { pushMatrix(); translate(location.x, location.y); if (behaviour==1) { fill(255, 0, 0); } else if ( behaviour==0) { fill(255, 255, 255); } ellipse(0, 0, 4, 4); strokeWeight(1); popMatrix(); } void checkEdges() { if (location.x < 0) { location.x = 0; velocity.x *= -1; acceleration.mult(0.001); } if (location.x > 800) { location.x = 800; velocity.x *= -1; acceleration.mult(0.001); } if (location.y < 0) { location.y = 0; velocity.y *= -1; acceleration.mult(0.001); } if (location.y > 800) { location.y = 800; velocity.y *= -1; acceleration.mult(0.001); } } void repel() { for (int i=0; i<numAgents; i++) { if ((agents[i].behaviour==1)) { int k; k=1; for (int j=0; j<numAgents; j++) { //-------------- // float dm = agents[i].location.dist(agents[k].location); float dm = dist(agents[j].location.x, agents[j].location.y, agents[i].location.x, agents[i].location.y); if (dm < 50) { agents[i].velocity.mult(-1); agents[i].acceleration.mult(0.5); agents[j].velocity.mult(-1); agents[j].acceleration.mult(0.5); } else if (behaviour==0) { agents[i].velocity.mult(1); agents[j].velocity.mult(1); } //float dm = dist(agents[i].location.x, agents[i].location.y, agents[j].location.x, agents[j].location.y); // float dm = agents[i].location.dist(agents[j].location); // int clr=(int) map (dm,0,100,200,0); if (dm<180 && dm>100) { if ( k<2) { //println(dm); //stroke(255,0,0); r1 = agents[j].location.x; r2 = agents[j].location.y; k=k+1; } else { //fill(random(255),random(255),random(255),random(0,20)); //stroke(0,50); // texture(A); //fill(random(0,255),random(0,255),random(0,255),random(0, 40)); // stroke(140, 50); fill(random(0, 255), random(0, 255), random(0, 255), random(0, 10)); stroke(140, 50); beginShape(); tint(255,127); texture(tex); vertex(agents[i].location.x, agents[i].location.y,0.0,0.0);//aditional u,v coordinates 0,0 - top left of texture vertex(r1, r2,1.0,0.0);//top right texture coordinate vertex(agents[j].location.x, agents[j].location.y,1.0,1.0);//bottom right texture coordinat endShape(CLOSE); j=300; } } } /*void triangulate() { fill(random(0, 255), random(0, 255), random(0, 255), random(0, 40)); stroke(140, 50); for (int i=0; i<numAgents; i++) { //gens[i].connect==true) //if(! agents[i].connect) if (agents[i].behaviour==1) { //println(agents[i]); int k; k=1; for (int j=0; j<numAgents; j++) { float dm = dist(agents[i].location.x, agents[i].location.y, agents[j].location.x, agents[j].location.y); // float dm = agents[i].location.dist(agents[j].location); // int clr=(int) map (dm,0,100,200,0); if (dm<180 && dm>100) { if ( k<2) { //println(dm); //stroke(255,0,0); } } } }*/ } } } } int numMovers= 1; Mover[]movers= new Mover[numMovers]; class Mover { PVector location; PVector velocity; PVector acceleration; float topspeed; boolean hit = false; Mover() { float spead = 800; location = new PVector(random(0,spead),random(0,spead)); velocity = new PVector(0,0); acceleration = new PVector(random(-1,1),random(-1,1));//random initial acceleration topspeed = 4; } void update() { // Motion 101! Velocity changes by acceleration. Location changes by velocity. velocity.add(acceleration); velocity.limit(topspeed); location.add(velocity); } void display() { pushMatrix(); translate(location.x,location.y); //fill(102,0,155,random(120,160)); //fill(32,225,245,127 + sin(frameCount*.01) * 127); if(hit) fill(255,10,96,120); else fill(3,225,190,random(50,127)); ellipse(0,0,30,30); noStroke(); popMatrix(); } void checkEdges() { if(location.x < 0){ location.x = 0; velocity.x *= -1; acceleration.mult(0.001); } if(location.x > 800){ location.x = 800; velocity.x *= -1; acceleration.mult(0.001); } if(location.y < 0){ location.y = 0; velocity.y *=- 1; acceleration.mult(0.001); } if(location.y > 800){ location.y = 800; velocity.y *= -1; acceleration.mult(0.001); } } }