typescript set x and y values to specific coordinates

Trying to map obstacles using a single object.

Originally scattered randomly across the map, now I want to hard code X & Y coordinates with an array of numbers. However, TypeScript is only using the last value of the loop for the X coordinate. How can I assign specific numbers to each obstacle?

Randomly Generate

module objects {
    export class Obstacles extends objects.GameObject {
        public Start():void {

            this.x = Math.floor(Math.random() * (640) - this.width) + this.halfWidth;
            this.y = Math.floor(Math.random() * (480) - this.width) + this.halfWidth;
            console.log("x " + this.x);
            console.log("y " + this.y);

  }
}

https://i.sstatic.net/5EBdA.jpg

Specify X Value With Array

private _obstX: number [] = [200, 250, 300, 350, 400];

public Start():void {

      for (let count = 0; count < this._obstX.length; count++) {
          this.x = this._obstX[count];
      }

      this.y = Math.floor(Math.random() * (480) - this.width) + this.halfWidth;
      console.log("x " + this.x);
      console.log("y " + this.y);

  }

https://i.sstatic.net/zrD22.jpg

Only one x value is being assigned, while the other x values in the array are ignored.

Code in Main File

private _obstPlanes: objects.Obstacles[];
private _obstNum: number;

public Start(): void {
  this._obstPlanes = new Array<objects.Obstacles>();
  this._obstNum = 5;


  for (let count = 0; count < this._obstNum; count++) {
    this._obstPlanes[count] = new objects.Obstacles(this.assetManager);
  }
}
public Main(): void {
  this._obstPlanes.forEach(obstPlane => {
      this.addChild(obstPlane);
  });
}

Answer №1

When you create a new instance of the Obstacles object, you iterate through the array _obstX to set the x property to the respective value from the array. All instances of Obstacles end up with an x value of 400 because the final iteration of the loop assigns this.x to the last value in the array.

To address this issue, I suggest moving the _obstX array to the main file and adding an x parameter or property to the constructor of your Obstacles class. The revised constructor could look something like this:

constructor(private assetManager: AssetManger, private x: number) {}

You can then instantiate the objects using:

new objects.Obstacles(this.assetManager, _obstX.shift())

This approach will pass the first element in _obstX to each constructor call and remove that element from the array. As a result, each instance of Obstacles will have a unique x value based on the values in the array.

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

Synchronizing data between parent and child components using two-way binding with emit in Vue 3 using TypeScript

Within my code, there is a child component: <template> <label :class="className + ' ctrl'"> <span><LocCtrl :page="pageName" :locKey="labelLoc" /></span> <input type=&q ...

The InMemoryCache feature of Apollo quietly discards data associated with fragments that are declared on the main

After sending the following query to my GraphQL server: fragment B on root_query { foo { id } } query A { ...B } The data received from the server includes the foo field. However, when I retrieve it using Apollo's InMemoryCache a ...

Whenever a file is chosen, I aim to generate the video HTML dynamically and display the video with play functionalities using Angular 2 and TypeScript

I am attempting to allow users to select a video file and display it so they can play it after choosing the file. Below is my HTML code: <br> <input type="file" (change)="fileChangeEvent($event)" placeholder="upload file..." class=" ...

How can I retrieve Json array data in android studio using volley?

Here is a JSON encoded array provided below:- { "imager": [{ "title": "Guru", "images": ["images\/6.png", "images\/androidIntro.png", "images\/barretr_Earth.png"] }] } The issue at hand is that I need to extract each image from th ...

Learn the process of setting up a connection between Express JS and the NotionAPI using both POST and

As someone who is new to backend development, I am currently working on integrating a simple Notion form into a Typescript website. To guide me through the process, I found a helpful tutorial at . The tutorial demonstrates how to send data from localhost:3 ...

Tips for maintaining a healthy balance of tasks in libuv during IO operations

Utilizing Typescript and libuv for IO operations is crucial. In my current situation, I am generating a fingerprint hash of a particular file. Let's say the input file size is approximately 1TB. To obtain the file's fingerprint, one method involv ...

Retrieve the response type from a Prisma FindUnique query

Essentially, my goal is to determine the type of the result obtained from a FindUnique operation in Prisma. The current return type is any: import prisma from "@/libs/prismaDb"; import { Prisma } from "@prisma/client"; export default a ...

Python's selenium struggles with iterating through elements

When attempting to iterate through a list of elements using the index of a class, the index doesn't increase with each attempt. If quotes are added around %s, it results in an invalid syntax error. lengeItem = len(driver.find_elements_by_xpath(&apos ...

"Utilizing a JavaScript array to track the start of the week and

I am encountering a logic problem with determining the start of the week. Below is a snippet of the code: WeekStarts(WeekN) { let WeekBD = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Sa ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

Make sure to incorporate the .gitignored files that are compiled from typescript when running the `npm install -g

Looking for a way to ignore the JavaScript files compiled from TypeScript in my git repository to make merging, rebasing, and partial commits easier. Here's how I have it set up: tsconfig.json { "compilerOptions": { "outDir": "./dist" ...

What are some ways to retrieve a summary of an Angular FormArray containing controls?

In my FormGroup, I have a FormArray called products which contains dynamic controls that can be added or removed: FormGroup { controls { products (FormArray) { 0 : {summary.value: 5}... 1 : {summary.value: 8}.. there can be N of these co ...

Extract Method Parameter Types in Typescript from a Generic Function

Can we retrieve the type of parameters of methods from a generic interface? For instance, if we have: interface Keys { create: any; ... } type MethodNames<T> = { [P in keyof Keys]: keyof T; } Then, is it feasible to obtain the type of paramete ...

Guidelines on sorting an array of strings by the presence of elements from another array of strings

Issue Resolved: Trouble Selecting Own Answer An issue arose when I tried to select my own answer for a problem I encountered. The problem involved loading an array from JSON into an NSMutableArray. Within this array, the entry "AllowedTo" contained a valu ...

Using i18next to efficiently map an array of objects in TypeScript

I am currently converting a React project to TypeScript and using Packages like Next.js, next-i18next, and styled-components. EDIT: The information provided here may be outdated due to current versions of next-i18next. Please check out: Typescript i18ne ...

Troubleshooting an Angular application

Just diving into Angular and following along with the tutorial on https://angular.io/tutorial. However, I seem to be facing an issue in Chrome where the const HEROES is not available in my watch list. It keeps showing as "not available". What could be ca ...

Spontaneous visual paired with text upon refreshing

I am new to Java script and I am working on creating a web page that displays two random numbers every time it is refreshed. Depending on these numbers, specific text should be shown. These numbers are represented by images ranging from 0 to 5. Currently ...

Analyze two sets of JSON data and compile a new JSON containing only the shared values

I am trying to generate two JSON arrays based on a shared property value from comparing two sets of JSON data. this.linkedParticipants =[ { "id": 3, "name": "Participant 2", "email": "<a href="/ ...

Is there a way to eliminate text from a barcode image using JavaScript or TypeScript?

This is my unique html code <div class="pr-2" style="width: 130px"> <div *ngIf="!element.editing" > <span class="ss">{{element.barcode}}</span> </di ...

The Extended Date type is indicating that the function cannot be located

I came across this helpful gist with date extensions: https://gist.github.com/weslleih/b6e7628416a052963349494747aed659 However, when attempting to use the functions, I encountered a runtime error stating: TypeError: x.isToday is not a function I foun ...