Using p5 library within a TypeScript class

Currently, I am diving into the world of p5 with the help of Coding train, but I have chosen to implement everything within a Typescript/webpack project.

In my code, I am utilizing p5 as an instance, and everything seems to be functioning correctly. However, I have a nagging suspicion that I might be making a mistake somewhere.

import * as p5 from 'p5';

export class Particlehelper {
  private pos: p5.Vector;
  private vel: p5.Vector;
  private accl: p5.Vector;

  public constructor(p: p5) {
    this.pos = p.createVector(p.random(p.windowWidth), p.random(p.windowHeight));
    // this.vel = p.createVector(0, 0);
    this.vel = p5.Vector.random2D();
    this.accl = p.createVector(0, 0);
  }

One aspect that is perplexing me is the fact that I am importing P5 specifically for its Vector properties, yet when it comes time to instantiate a vector, I need to pass P5 to the constructor from the index file.

particles[i] = new Particlehelper(p);

This method feels redundant - it seems like I am essentially calling upon P5 twice. Despite my efforts, I cannot seem to figure out how to solely utilize the imported p5 object within the class.

Additionally, the notation of "public constructor" is unfamiliar to me. My linter prompted me to include it, but I am unsure if this is the correct approach or not.

Any insights would be greatly appreciated.

Answer №1

This snippet of code is perfectly functional. The unique aspect of p5.Vector lies in its unconventional qualities - it does not explicitly define its constructor arguments and can be initialized with a reference to a p5 instance. This design allows for the consideration of the sketch's angle mode (DEGREES or RADIANS) in certain p5.Vector functions. When creating a p5.Vector using createVector, the resulting vector retains a connection to the p5 instance and adheres to its angle mode settings. However, statically created vectors do not follow the sketch's angle mode:

    p.angleMode(p.DEGREES);

    let v1 = p.createVector(1, 0);
    let v2 = p.createVector(0, 1);
    // Angle between v1 and v2 displayed in degrees
    console.log(v1.angleBetween(v2));

    v1 = new p5.Vector();
    v1.set(1, 0);
    v2 = new p5.Vector();
    v2.set(0, 1);
    // Angle between v1 and v2 displayed in radians
    console.log(v1.angleBetween(v2));

It should also be noted that p5.Vector.random2d creates vectors using the default angle mode of radians.

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

Set the styling of a div element in the Angular template when the application is first initialized

I have a question about this specific div element: <div class="relative rounded overflow-clip border w-full" [style.aspect-ratio]="media.value.ratio"> <img fill priority [ngSrc]="media.value.src || ftaLogo" ...

"Creating a visual representation of models exchanged between the client and server through Rest

Currently, I am working on a project that involves client-server communication via rest API, with Angular 2 calling restful web services as the primary method. The client side is written in Typescript, which is a subset of JavaScript. My main challenge li ...

When the page hosted on Vercel is reloaded, `getStaticProps` does not function as expected

I'm currently working on a nextjs project and running into an issue where one of the pages returns a 404 error when it's reloaded. Within the page directory, I am using getStaticProps. pages - blogs.tsx - blog/[slug].tsx - index.tsx ...

Having trouble connecting to Cloud Firestore backend using Angular Universal and Firebase Functions?

When attempting to make a basic request to Firestore on the server side using Angular Universal with firebase serve, I encountered an issue with connecting to Firestore. Here is the code snippet: constructor(private afs: AngularFirestore) { this.afs. ...

Exploring Angular2's interaction with HTML5 local storage

Currently, I am following a tutorial on authentication in Angular2 which can be found at the following link: https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492 I have encountered an issue with the code snippet below: import localSt ...

The element type 'HTMLElement' does not contain a property named 'pseudoStyle'

Currently experimenting with adjusting the height of a pseudo element using Typescript. An error is popping up in my IDE (vscode) as I go along. This is the code snippet I am working with. // choose element let el: HTMLElement = document.getElementById( ...

Production environment sees req.cookies NEXTJS Middleware as undefined

Here is my latest middleware implementation: export async function middleware(request: NextRequest) { const token = request.headers.get('token') console.log(token) if (!token || token == undefined) { return NextResponse.redirect(new URL('/lo ...

Creating an Http Service Instance in Angular 2 by Hand

Can the Http Service be initialized manually without needing it as a constructor argument? export class SimpleGridServer { private http: Http; constructor(public options: SimpleServerData) { http = new Http(.../* Argument here */); } } ...

In Angular 2 rc1, the component provider will only function properly if it is defined within the root

I am working on an Angular2 component that requires the injection of a service called KeyValueService in its constructor. This service is used to patch the new router's missing data on routes. KeyValueService import {Injectable} from '@angular/ ...

What exactly do we mean by the term 'object literal' within the realm of TypeScript?

When diving into TypeScript, the term 'object literal' comes up frequently (like in this answer) - but what exactly does 'object literal' mean and how is it different from just an 'object'? For more insight, you can check out ...

Angular search results coming back as null

I am currently building a search feature for my app (using Angular 14 + Ionic 6) that searches via API call using the GET method. Struggling with an issue where it keeps returning 'undefined' in the console, and also encountering a problem with a ...

Decipher intricate JSON data using Typescript

When a request receives a response, it is delivered in JSON format. The specific structure of the JSON data is as follows: { "32": { "docKey": "32", "outletId": 32, "mdngOutlet": { "outletBasic": { "outletId": 32, } ...

Creating efficient React components with TypeScript and leveraging generic props

I’ve been working on understanding and resolving my issue with React components' generic props. I came across a code example in an article about using TypeScript with functional React components and generic props. Unfortunately, when trying to repli ...

What could be causing the content in my select box to change only when additional select boxes are introduced?

When working with a form in next.js and using select boxes from material UI, I encountered an issue. The number of select boxes should change based on user input, but when I modify the value inside a select box, the displayed text does not update until I a ...

Include a Polyfill in craco, implementing a fallback for 'resolve.fallback'

I'm encountering an issue: If you need to use a polyfill, follow these steps: - include a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }' - install 'path-browserify' If you prefer n ...

Get the HTML file converted to a DOCX format that is compatible with Mac Pages

I am currently working on a Next.js application using TypeScript, and I want to give users the ability to download a page as a DOCX file. Initially, I was excited to discover that this could be easily accomplished by following this method. However, after ...

Guide on incorporating the authorization function from next-auth into a TypeScript Next.js 13 app directory

Can you help me understand the proper way to declare the authorize function in [...nextauth].ts? I have been attempting it as shown below: export default NextAuth({ session: { strategy: "jwt" }, providers: ...

Function that returns a lookup map for TypeScript enums

For my React project, I've created a function that transforms a lookup class into an array that can be used. The function is functioning properly, but it seems to loop through the enum twice, resulting in undefined values for the first iteration. Alt ...

Creating multiple copies of a form div in Angular using Typescript

I'm attempting to replicate a form using Angular, but I keep getting the error message "Object is possibly 'null'". HTML: <div class="form-container"> <form class="example"> <mat-form-field> ...

The localStorage retrieval function is returning a null value for getItem

I successfully incorporated a theme switcher into my app, enabling users to toggle between different theme/variable.scss files using an on/off switch in the interface. However, I encountered an issue with storing and retrieving user preferences. While I m ...