Attempting to transform open processing code into p5.js

I am struggling to convert this code into p5.js format and looking for assistance with the conversion process. I understand that there may be differences in syntax between regular Java and p5.js, especially with arrays. Any help on getting this code to function correctly in p5.js would be greatly appreciated.

    Myself myself;
ArrayList<Enemy> enemies;
`enter code here`ArrayList<Enemy> enemies;
ArrayList<Bullet> myBullets;
ArrayList<Bullet> eneBullets;

function setup(){

  createCanvas(640, 640);
  rectMode(CENTER);
  myself = new Myself();
  enemies = new ArrayList<Enemy>();
  myBullets = new ArrayList<Bullet>();
  eneBullets = new ArrayList<Bullet>(); 
}

function draw(){
  background(0);
  myself.display();
  for(let i = 0; i < enemies.length; i++){
    enemy[i].display();
  }
  for(let i = 0; i < myBullets.length; i++){
    bullet[i].display();
  }
  for(let i = 0; i < eneBullets.length; i++){
    bullet[i].display();
  }

  myself.update();
  let nextEnemies = [];
  for(let i = 0; i < enemies.length; i++){
    enemy[i].update();
    if(!enemy[i].isDead){
      nextEnemies.push(enemy[i]);
    }
  }
  enemies = nextEnemies;
  let nextMyBullets = [];
  for(let i = 0; i < myBullets.length; i++){
    bullet[i].update();
    if(!bullet[i].isDead){
      nextMyBullets.push(bullet[i]);
    }
  }
  myBullets = nextMyBullets;
  let nextEneBullets = [];
  for(let i = 0; i < eneBullets.length; i++){
    bullet[i].update();
    if(!bullet[i].isDead){
      nextEneBullets.push(bullet[i]);
    }
  }
  eneBullets = nextEneBullets;
  if(random(1) < 0.02){
    enemies.push(new Enemy());
  }
}

class Myself{

  let loc;
  let size;
  let coolingTime;
  let isDead;

  Myself(){
    size = 25;
    loc = createVector(width / 2, height - size / 2 - 10);
    coolingTime = 0;
    isDead = false;
  }

  display(){
    if(isDead){
      fill(255, 255, 0);
      stroke(0, 255, 0); 
    } else {
      noFill();
      stroke(0, 255, 0);
    }
    rect(loc.x, loc.y, size, size);
  }

  update(){
    isDead = false;
    let dmx = mouseX - loc.x;
    dmx = constrain(dmx, -5, 5);
    loc.x += dmx;
    coolingTime++;
    if(mouseIsPressed && coolingTime >= 10){
      myBullets.push(new Bullet());
      coolingTime = 0;
    }
    for(let j = 0; j < eneBullets.length; j++){
      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(let k = 0; k < enemies.length; k++){
      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;
      }
    }
  }
}

If you could provide guidance on what changes need to be made or fixed within the code, it would greatly assist me. Thank you.

Answer №1

Translating code line-by-line is not the most effective approach. It's better to take a step back, understand the program's functionality, and then replicate that in the target language.

The syntax of Processing (based on Java) differs greatly from p5.js (based on JavaScript).

Instead of attempting to directly "convert" the code, focus on understanding its purpose. Then, create a new program using p5.js and implement the same functionality. It may not always be a straightforward line-by-line translation.

Answer №2

Here is the code snippet provided:

 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");
}
}

We apologize for any collision issues you may encounter when converting from Processing to p5.js. Here are some tips:

1: Use arrays with push instead of ArrayLists. 2: Only use "let" for data types. 3: Utilize "print" instead of "println". 4: Declare class constructors as "constructor" rather than the class name. 5: Prefix function declarations with "function" instead of void. 6: Replace PVector with vector. 7: Remember that Google can be a helpful resource. 8: Refer to the p5.js documentation for guidance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we use the Vertx router in Quarkus to automatically redirect all unknown routes to index.html?

I have a unique setup with my Quarkus application where I package an Angular SPA within the JAR file. The backend API routes are provided by Quarkus for the front end to consume. During the build process of the Quarkus application, the Angular application ...

Tips for adjusting image size to take up only half of the screen in NextJS

Struggling to resize an image to fit only 50% of the screen in NextJS? The Image component provided by NextJS comes with its own inline styling, making it tricky to customize. Currently, I attempt to style the image by wrapping the Image component in a spa ...

Trouble centering a list within a parent div using CSS

Even though this issue seems straightforward and many others have asked similar questions on the site, I find myself stuck after reading through several solutions and attempting various fixes. Why is this happening? My problem involves centering a navigat ...

Retrieve the text enclosed by br tags using Selenium in JAVA

I am struggling to extract the texts 'Texas-United States' and 'Illinois-United States' in order to click on the hyperlink located above the text after matching the strings. I have attempted various methods but have been unsuccessful so ...

The absence of the `breakInside` rule in GrooCSS

Currently, I am utilizing GrooCSS 1.0-GA for my CSS coding needs. Regrettably, it appears that GrooCSS does not provide support for breakInside as illustrated in the code snippet below: GrooCSS.process(new Config(prettyPrint: true)) { body { breakIns ...

What are the most effective strategies for incorporating the Java module system into an educational environment?

My role involves teaching Java programming courses at a college level. It seems logical to incorporate the latest LTS version (Java 11) into the curriculum. We focus on JavaFX for user interfaces, but the JavaFX module system can be difficult for beginners ...

Full-width header with scrollable content within the viewport

Is there a way to make the header and footer expand to 100% width while keeping the middle content width variable? You can view the source at http://jsfiddle.net/9dWcZ/ HTML: <div class="header"> this is header </div> <div class="content ...

Creating a custom video to use as the favicon for my website

Imagine this: With the help of this plugin, you can have a video playing as your site's favicon using the following code snippet: var favicon=new Favico(); var video=document.getElementById('videoId'); favicon.video(video); //stop favicon.v ...

Uncover the hidden message within the unique special character "ì"

My JSON file contains a specific character, such as ì; Here is the service I am using: $http({ url: jsonUrl, method: "GET" }).success(function (data) { // data is an array that contains a list of elements (f ...

Each time a nested collapse occurs, it triggers its parent collapse

I have come across some similar answers, but they all pertain to accordions, which I am not utilizing in this case. In my code, I have nested collapse items. You can view the code snippet here on CodePen $('#collapseOutter').on('show.bs. ...

How can I assign a default value to an angular 2+ dropdown menu? [I have not found a solution in previous inquiries]

When I attempt to set a default value with an empty channelId, it works as expected. Here is the example code snippet: destChannelList = [ { "channelId":"", "channelName":"SMS" }, { "channelId":1, "channelName":"Voice" ...

Is it possible for an object to contain an array of objects of the same type?

The Object Accounts that I am dealing with contains sub Accounts as well. Both the parent Accounts and children Accounts have a similar structure where there is one parent account associated with multiple children. These two types of accounts need to be m ...

The breakdown of an object literal in JavaScript

What is the reason that we cannot access the second item in the object literal the same way as the first? var foo = {a:"alpha",2:"beta"}; console.log(foo.a) -> printing 'alpha' correctly console.log(foo.2) -> Error: missing ) after argumen ...

Placing a floating image in the lower right-hand corner, for instance

I'm trying to place a transparent image in the bottom-right corner of my page. I've looked up solutions for top-right and right corners, but I've only managed to make it work using 'margin-top: 100%;', which causes a scroll bar to ...

Tips for identifying the clicked location inside an element using JavaScript?

Is there a way in JavaScript to find out the exact position of a click within an element, like its distance from the left, right, or center? I'm struggling to determine whether the clicked area is on the left, center, or right side. https://i.stack.i ...

Creating a dynamic text design using Bootstrap or CSS: What's the best approach?

I attempted to enable responsive font sizes in Bootstrap 4.3.1 by setting the $enable-responsive-font-sizes variable to true, but I did not see any changes. Below is the code from my template.html file: <div class="m-2" id="role" ...

Replicating radio button functionality using buttons in an HTML document

I am attempting to simulate radio button behavior using normal buttons for a quiz application. Currently, my code is working as intended and permanently highlights buttons with the desired color. However, I want all other buttons in a question to be white, ...

Tips on positioning a div based on the screen dimensions

In my table, there is an icon that reveals a chart as a popup when hovered over. This div is where the chart is displayed: <div id="chart-outer" style="@style" class="popup-chart close"> <h2 id="charttitle&q ...

Striving to implement a dynamic expand and collapse animation feature for a card in ReactJS

I'm attempting to create an expand and collapse animation effect on a card without relying on bootstrap or any external libraries. I have tried adding a transition property but it doesn't seem to work when the button is clicked. Here is the comp ...

Keeping the scroll in place on a Bootstrap4 modal while scrolling through content that is already at the top

On my Bootstrap 4 modal, I have encountered an issue with scrollable content. When I am at the top of the content and try to scroll downwards, nothing happens because I am already at the top. However, if I continue to hold the touch without releasing it, t ...