How to use setUserPointer/getUserPointer from Ammo.js - javascript

I want to print names of colliding objects. I made a very simple example.
I created an object to keep a user data:
const userData = { name: name };
I keep this object in a body using setUserPointer:
body.setUserPointer(userData);
I try to get this names using getUserPointer and print them. But I get "undefined" instead of names:
function detectCollison(): void
{
const dispatcher = physicsWorld.getDispatcher();
const numManifolds = dispatcher.getNumManifolds();
for (let i = 0; i < numManifolds; i++)
{
const contactManifold = dispatcher.getManifoldByIndexInternal(i);
const body0 = contactManifold.getBody0();
const body1 = contactManifold.getBody1();
const p0 = body0.getUserPointer();
const p1 = body1.getUserPointer();
console.log("first object: " + p0.name);
console.log("second object: " + p1.name);
}
}
Edited
This is pure TypeScript version. I tried to keep names as a body property but it does not work too. It prints "undefined" instead of names:
(this.body as any).name = name;
physicsWorld.addRigidBody(this.body);
function detectCollison(): void
{
const dispatcher = physicsWorld.getDispatcher();
const numManifolds = dispatcher.getNumManifolds();
for (let i = 0; i < numManifolds; i++)
{
const contactManifold = dispatcher.getManifoldByIndexInternal(i);
const body0 = contactManifold.getBody0();
const body1 = contactManifold.getBody1();
console.log("first object: " + (body0 as any).name);
console.log("second object: " + (body1 as any).name);
}
}

Solution:
const userData = { name: name };
(this.body as any).userData = userData;
function detectCollison(): void
{
const dispatcher = physicsWorld.getDispatcher();
const numManifolds = dispatcher.getNumManifolds();
for (let i = 0; i < numManifolds; i++)
{
const contactManifold = dispatcher.getManifoldByIndexInternal(i);
const body0 = contactManifold.getBody0();
const body1 = contactManifold.getBody1();
const rb0 = (Ammo as any).castObject( contactManifold.getBody0(), Ammo.btRigidBody );
const rb1 = (Ammo as any).castObject( contactManifold.getBody1(), Ammo.btRigidBody );
console.log("first object:", rb0.userData);
console.log("second object:", rb1.userData);
}
}

Related

How can get totalBalanceAmount value from getSavingsInput() and put into (HERE)?

How can get totalBalanceAmount value from getSavingsInput() that i can put into (HERE)?
function getSavingsInput() {
let totalBalance = document.getElementById('balance')
let totalBalanceAmount = parseFloat(totalBalance.value)
return totalBalanceAmount;
}
document.getElementById('Savings').addEventListener('click',function() {
let savingInput = getInput('savigns-input') // this is the another function
let savingsInputAmount = parseFloat(savingInput)
const savignsAmount = (HERE) % savingsInputAmount;
const savedAmount = document.getElementById('saved-amount')
savedAmount.innerText = savignsAmount;
})

reading from csv file returns undefined value

For some reason, when I am reading a CSV file with React, I am getting undefined as the values, and I am not sure why this is happening. Below is the general format of my .csv file.
Date,Site,Depth (m),Temp (degC),SpeCond(uS/cm),Chla (ug/L),Turb (FTU),DO (mg/L)
Mar-18-2019,UA01,-0.518,10.9387,233.3824,4.2043,11.118,10.7842
Mar-18-2019,UA01,-0.585,10.9352,233.4042,4.4753,11.272,10.7935
Mar-18-2019,UA01,-0.651,10.9335,233.3973,4.641,11.26,10.7987
Mar-18-2019,UA01,-0.717,10.9319,233.4335,4.7184,10.985,10.796
Mar-18-2019,UA01,-0.785,10.9292,233.4137,4.8404,10.985,10.7938
Mar-18-2019,UA01,-0.85,10.9268,233.4009,5.0127,11.158,10.7885
Mar-18-2019,UA01,-0.909,10.9257,233.4585,5.1674,11.662,10.78
Mar-18-2019,UA01,-0.969,10.9248,233.4452,5.3253,11.249,10.7753
Mar-18-2019,UA01,-1.04,10.9241,233.3777,5.5321,10.852,10.7706
...
This is my App.js:
import React,{useState} from "react";
import * as $ from 'jquery';
import ReactDOM from 'react-dom'
import Highcharts from 'highcharts';
export default function App() {
const [selects, setSelects] = useState();
return (
<div className="App">
<h1>{selects}</h1>
<h3 className = "form-labels"> Visuals: </h3>
<select value = {selects} onChange = {e=>printSelected(e.target.value) }>
<option>Temperature</option>
<option>Special Conductivity</option>
<option>Chlorophyll</option>
<option>Turbosity</option>
<option>Dissolved Oxygen</option>
</select>
<select value = {selects} onChange = {e=>printSelected1(e.target.value) }>
<option>UA01</option>
<option>UA01_SB19</option>
<option>UA01_SB25</option>
<option>UA06</option>
<option>UA06_SB19</option>
<option>UA06_SB25</option>
<option>UA07</option>
<option>UA07_SB19</option>
<option>UA07_SB25</option>
<option>UA08</option>
<option>UA08_SB19</option>
<option>UA08_SB25</option>
<option>LA03</option>
<option>LA03_SB19</option>
<option>LA03_SB25</option>
<option>NR02</option>
<option>NR02_SB19</option>
<option>NR02_SB25</option>
<option>OA04</option>
<option>OA04_SB19</option>
<option>OA04_SB25</option>
</select>
</div>
);
}
const x = [];
const y = [];
var tab = [];
var tab1 = [];
var tab2 = [];
var tab3 = [];
var tab4 = [];
var response = "";
var data = "";
var sortedD = [];
var sortedD1 = [];
var sortedD2 = [];
var sortedD3 = [];
var sortedD4 = [];
var fileName = "UA01";
var visuals = "Temp";
function printSelected(e) {
sortedD.length = 0;
tab.length = 0;
sortedD1.length = 0;
tab1.length = 0;
sortedD2.length = 0;
tab2.length = 0;
sortedD3.length = 0;
tab3.length = 0;
sortedD4.length = 0;
tab4.length = 0;
visuals = e;
getChart();
}
function printSelected1(e) {
sortedD.length = 0;
tab.length = 0;
sortedD1.length = 0;
tab1.length = 0;
sortedD2.length = 0;
tab2.length = 0;
sortedD3.length = 0;
tab3.length = 0;
sortedD4.length = 0;
tab4.length = 0;
fileName = e;
getChart();
}
async function getChart() {
await getData();
var data1 = [];
var name1 = "";
if (visuals.localeCompare("Temp") === 0) {
data1 = sortedD;
name1 = "Temperature (deg Celsius) ";
} else if (visuals.localeCompare("Special Conductivity") === 0) {
data1 = sortedD1;
name1 = "Special Conductivity (uS/cm) ";
} else if (visuals.localeCompare("Chlorophyll") === 0) {
data1 = sortedD2;
name1 = "Chlorophyll (ug/L) ";
} else if (visuals.localeCompare("Turbosity") === 0) {
data1 = sortedD3;
name1 = "Turbosity (FTU) ";
} else {
data1 = sortedD4;
name1 = "Dissolved Oxygen (mg/L)";
}
}
async function getData() {
response = await fetch(fileName + ".csv");
data = await response.text();
const table = data.split('\n').slice(1);
table.forEach(row => {
const col = row.split(',');
const depth = col[2];
var ele = [];
var ele1 = [];
var ele2 = [];
var ele3 = [];
var ele4 = [];
console.log("Depth: " + depth);
console.log("Val: " + col[3]);
ele.push(parseFloat(col[3]));
ele.push(parseFloat(depth));
ele1.push(parseFloat(col[4]));
ele1.push(parseFloat(depth));
ele2.push(parseFloat(col[5]));
ele2.push(parseFloat(depth));
ele3.push(parseFloat(col[6]));
ele3.push(parseFloat(depth));
ele4.push(parseFloat(col[7]));
ele4.push(parseFloat(depth));
tab.push(ele);
tab1.push(ele1);
tab2.push(ele2);
tab3.push(ele3);
tab4.push(ele4);
})
sortedD = tab.sort((a,b) => b[0]-a[0]);
sortedD1 = tab1.sort((a,b) => b[0]-a[0]);
sortedD2 = tab2.sort((a,b) => b[0]-a[0]);
sortedD3 = tab3.sort((a,b) => b[0]-a[0]);
sortedD4 = tab4.sort((a,b) => b[0]-a[0]);
}
getChart();
I am trying to build a dropdown menu to display different line graphs depending on what dropdown is selected, but for some reason when I try to print values of my variables I am trying to plot, I get undefined. And the length of the arrays I have made are always 43 for some reason...
Depth: undefined
Val: undefined
Depth: undefined
Val: undefined
Depth: undefined
Val: undefined
Depth: undefined
Val: undefined
Depth: undefined
Val: undefined
Depth: undefined
I have a feeling that it might be the await fetch and await response, but I am not 100% sure. Any tips on this would be greatly appreciated!

How to get variable in set method

I have an issue with getting a variable in a setter method when I create a class.
In the picture above you can see my method "set quest" returns this (num 1) instead of this.questId (num 2) . How can I get this.questId in "set" and what I am doing wrong? Thank you in advance.
class TestItem {
constructor(testItem) {
this.quest = testItem.quest;
this.answList = testItem.answList;
this.questId = testItem.id;
}
set quest(value) {
console.log(this , this.questId);
let questItem = document.createElement('div');
questItem.classList.add('questItem');
questItem.textContent = `${this.questId}. ${value}`;
this._quest = questItem;
}
set answList(value) {
this._answList = value.map((item, i) => {
let answItem = document.createElement('span');
answItem.classList.add('answItem');
answItem.setAttribute('data-value', item.val);
answItem.textContent = item.answ;
return answItem;
});
}
getQuestBlock() {
let questBlock = document.createElement('div');
questBlock.classList.add(`quest${this.questId}`);
questBlock.append(this._quest);
this._answList.forEach(item => questBlock.append(item));
console.log(questBlock);
return questBlock;
}
}
function createTest(testData) {
let testContainer = document.querySelector('#testContainer');
testData.forEach((item, i) => {
let testItem = new TestItem(item);
let questBlock = testItem.getQuestBlock();
testContainer.append(questBlock);
});
}
document.addEventListener("DOMContentLoaded", createTest.bind(this ,testData));

Very new to Javascript OOP: Passing a value to property through input fails to render single Element

I'm having problems rendering individual "li" elements through OOP approach.
I'm fetching the input from the user and using this info to create an item through a class. I'm then connecting this class to the list class responsible for rendering the list.
Once I fetch the value through a click event listener, the singleTaskRendering class isn't working. I wonder if I'm setting this up incorrectly?
const inputAccess = document.querySelector('.control').querySelector('input');
const addItemBtnAccess = document.getElementById('add-item-btn');
const toDoList = [];
const doneList = [];
//ads a li id to the item
const idGenerator = (array) => {
let n = 1;
let message = '';
for (let i = 0; i < array.length; i++) {
n += 1;
}
message = `li-${n}`;
return message;
}
class ItemTask {
constructor(itemValue, idGen) {
this.title = itemValue;
this.id = idGen;
}
}
const addItemBtnHandler = () => {
const toDoList = [];
const inputValue = inputAccess.value;
const item= new ItemTask(inputValue, idGenerator(toDoList));
toDoList.push(item);
return toDoList;
};
class singleTaskRendering {
constructor(product) {
this.product = product;
}
render() {
const titleElement = document.createElement('div');
titleElement.id = this.product.id;
titleElement.innerHTML = `
<li>
<h2>${this.product.title}</h2>
<button>Done</button>
<button>Delete</button>
</li>`;
titleElement.draggable = true;
}
}
class ItemLists {
constructor(listId, items) {
this.items = items;
this.listId = listId;
console.log(this.items, this.listId);
}
renderList() {
const renderHook = document.getElementById('hook');
const createList = document.createElement('lu');
createList.className = 'card';
createList.id = `${this.listId}-list`;
for(let item of this.items) {
const newItem = new singleTaskRendering(item);
console.log(newItem);
const itemEl = newItem.render();
console.log(itemEl, newItem);
createList.apppend(itemEl);
}
renderHook.append(createList);
}
}
const itemList = new ItemLists('active', toDoList);
itemList.renderList();
addItemBtnAccess.addEventListener('click', addItemBtnHandler);
The problem that you are having is that you call ItemLists on page load, which means it will only be processing an empty toDoList.
My solution is to rename renderList to appendItem.
Declare it at the top
Don't pass the list id and list to the constructor instead pass it to
appendItem in the clickhandler.
const inputAccess = document.querySelector('.control').querySelector('input');
const addItemBtnAccess = document.getElementById('add-item-btn');
const itemList = new ItemLists();
const toDoList = [];
const doneList = [];
//ads a li id to the item
const idGenerator = (array) => {
let n = 1;
let message = '';
for (let i = 0; i < array.length; i++) {
n += 1;
}
message = `li-${n}`;
return message;
}
class ItemTask {
constructor(itemValue, idGen) {
this.title = itemValue;
this.id = idGen;
}
}
const addItemBtnHandler = () => {
const toDoList = [];
const inputValue = inputAccess.value;
const item= new ItemTask(inputValue, idGenerator(toDoList));
itemList.appendItem('active', item);
};
class singleTaskRendering {
constructor(product) {
this.product = product;
}
render() {
const titleElement = document.createElement('div');
titleElement.id = this.product.id;
titleElement.innerHTML = `
<li>
<h2>${this.product.title}</h2>
<button>Done</button>
<button>Delete</button>
</li>`;
titleElement.draggable = true;
}
}
class ItemLists {
appendItem(listId, item) {
const renderHook = document.getElementById('hook');
const createList = document.createElement('lu');
createList.className = 'card';
createList.id = `${listId}-list`;
const newItem = new singleTaskRendering(item);
console.log(newItem);
const itemEl = newItem.render();
console.log(itemEl, newItem);
createList.apppend(itemEl);
renderHook.append(createList);
}
}
addItemBtnAccess.addEventListener('click', addItemBtnHandler);

Why is my function not returning the desired value, however, console.log() does the job?

I know this question might be a little basic but I think I am lacking some important fundamental concept. I am coding in node.js, and I have a function getPostInfo(). In the end, I have a return statement that returns the object that I created. However, when I run it on PowerShell I get no output. Furthermore, when I console.log(object) I get the required answer.
If someone knows what I might be doing wrong, let me know.
P.S. - The major chunks of code in the middle can be skipped as they are just to get information of a webpage
const cheerio = require('cheerio');
const axios = require('axios');
let object = {};
const getPostInfo = async () => {
const {data} = await axios.get('https://www.imdb.com/search/title/?groups=top_1000&ref_=adv_prv');
// console.log(data)
const $ = cheerio.load(data);
const titles = [];
const date = [];
const runtime = [];
const rating = [];
const metascore = [];
const votes = [];
const grossEarning = [];
$('h3 a').each((i, el) => {
titles[i] = $(el).text().trim();
})
$('h3 .lister-item-year').each((i, el) => {
date[i] = $(el).text();
})
$('.runtime').each((i, el) => {
runtime[i] = $(el).text().trim();
});
$('.ratings-imdb-rating').each((i, el) => {
rating[i] = $(el).text().trim();
})
$('.ratings-bar').each((i, el) => {
if ($(el).find('.ratings-metascore .favorable').length > 0) {
metascore[i] = $(el).find('.ratings-metascore .favorable').text().trim();
}
if ($(el).find('.ratings-metascore .mixed').length > 0) {
metascore[i] = $(el).find('.ratings-metascore .mixed').text().trim();
}
})
const nv = [];
$('.sort-num_votes-visible').each((i, el) => {
if($(el).find('span')){
// text-muted has text 'votes:', however we need the number of votes which is in next() span tag
nv[i] = $(el).find('.text-muted').next().text();
votes[i] = nv[i].split('$')[0];
grossEarning[i] = '$' + nv[i].split('$')[1];
}
})
for (let i = 0; i < 50; i++) {
object[i] = {
title: titles[i],
date: date[i],
runtime: runtime[i],
rating: rating[i],
metascore: metascore[i],
votes: votes[i],
grossEarning: grossEarning[i]
};
}
// This does not work but console.log(object) gives me a list of objects
return object
// console.log(object);
}
getPostInfo()

Categories

Resources