How do I do ray based (continuous) collision JS?

I am making a brick breaker game in JavaScript. I want to add continuous collision detection.
Such that if the ball(circle) were to collide with a brick(rectangle) between frames the ball’s position and velocity update based on where they would have collided (let collidePointX = BALL.x – BRICK.x;).

It seems that the way to do this is draw collision from a ray of (the ball’s velocity vector + the ball’s radius) but that ray’s collision doesn’t reflect where the ball’s x,y would have been if it collided naturally.

to reiterate I need to determine the x&y collide points (let collidePointX = BALL.x – BRICK.x;) when my ball would collide between frames.

How do I solve this?

Is there terminology for this?

Is there a library that solves this?

Is the solution different for (circle/rectangle) vs.(circle/circle) collisions?

I’m super new and feel way over my head with this one. It’s proving difficult to Google.

Uncaught SyntaxError: Unexpected token ‘if’ with beginer

I don’t know the Uncaught SyntaxError: Unexpected token ‘if’

var fee = Number($(this).find('.fee').text());

if(subtotal <= 9999){
  fee = 330;

}esle if(subtotal <= 29999 && subtotal > 9999){ //error in here
  fee = 440;

}esle if(subtotal <= 99999 && subtotal > 29999){
  fee = 660;

}esle (subtotal <= 300000 && subtotal > 99999){
  fee = 1100;
}

console.log(fee);

Using JavaScript how do I get the padding/margin settings to always retrieve the CSS set % and not px size

For a div with css of {padding:10% 10px 20% 10px;} I need to be able to retrieve via JavaScript the padding as it is set but window.getComputedStyle(myelement).getPropertyValue(‘padding’); returns different results.

Firefox = “10% 10px 20% 10px”

Chromium = “59.8839px 10px 119.768px 2px”

Is there any other way to retrieve this info so it gets the % values and not the elements current state px value?

http://jsfiddle.net/o1jhbn9f/1/

var div = document.getElementsByTagName('div')[0];
console.log(window.getComputedStyle(div).getPropertyValue('padding'));

ReactJs Firebase cookies

In my ReactJs project im using the Authentication feature of Firebase , when i try to register a new user to the authetication data base it fails and i get the following message in my console , will anyone explains how fix that ?

Because a cookie’s SameSite attribute was not set or is invalid, it
defaults to SameSite=Lax, which prevents the cookie from being sent in
a cross-site request. This behavior protects user data from
accidentally leaking to third parties and cross-site request forgery.
Resolve this issue by updating the attributes of the cookie: Specify
SameSite=None and Secure if the cookie should be sent in cross-site
requests. This enables third-party use. Specify SameSite=Strict or
SameSite=Lax if the cookie should not be sent in cross-site requests.

Why isn’t any JS echoing back to the file which is calling it?

I have been trying to figure why none of the JS I try to echo is echoing. To summarise my project I have a function which calls a PHP file and then the PHP file sends information back. It can send information which is not in JS but as soon as I try JS nothings come about. I have even tried a basic console.log(); and still nothing.

Does anybody have an idea on why this is?

Below is the file which is calling.

<html>
<link rel="stylesheet" type="text/css" href="styles.css">
<div class="HogMainContent">
<button name="Subtract" onclick=subtract()>Previous Game</button>
<button name="Add" onclick="add()">Next Game</button>
<div id="insertion"></div>
<script>
var count = 0;
function send(item) {
  const xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function() {
      document.getElementById("insertion").innerHTML = this.responseText;
    }
    xmlhttp.open("GET", "gather.php?q=" + item);
    xmlhttp.send();
}
function subtract() {
  count--;
  send(count);

}
function add() {
  count++;
  send(count);
}
</script>
</div>
</html>

Below is the file which is being called. This is where no JS is working.

<?php
$host = "localhost";
$username = "root";
$password = "";
$db = "ia2";
$link = mysqli_connect($host, $username, $password, $db);
if($link === false) {
  die("Error: Couldn't Connect." . mysqli_connect_error());
}
$q = $_REQUEST["q"];
$sql = "SELECT * FROM vgsales WHERE `Rank`=$q";
if($result = mysqli_query($link, $sql)){
  if(mysqli_num_rows($result)>0) {
    while($row=mysqli_fetch_array($result)){
      echo $row['Rank'];
      echo $row['Name'];
      echo $row['Platform'];
      echo $row['Year'];
      echo $row['Genre'];
      echo $row['Publisher'];
      echo $row['NA_Sales'];
      echo "
      <script type='text/javascript' src='https://www.gstatic.com/charts/loader.js'></script>
      <div id='myChart' style='width:100%; max-width:600px; height:500px;''></div>
      <script type='text/JavaScript'>
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
      var data = google.visualization.arrayToDataTable([
        ['Sales Region', 'Number of Sales']
        ['NA Sales',". $row['NA_Sales']."],
        ['EU Sales',". $row['EU_Sales']."],
        ['France',". $row['JP_Sales']."],
        ['Spain',".$row['Other_Sales']."],
      ], true);
      var options = {
        title:'Game Sales". $row['Name']."'
      };
      var chart = new google.visualization.PieChart(document.getElementById('myChart'));
      chart.draw(data, options);
      }
      </script>
      ";
    }
    mysqli_free_result($result);
  }
}
else {
  echo "Error: Could not execute $sql" . mysqli_error($link);
}
mysqli_close($link);
?>

chart.js – show duplicate y-axis on left and right sides

I know similar questions have been asked many times before, but most results are for older versions and the API has changed a lot. I could not find code for 3.5+ that “just works”.

I’m wondering if there’s a better way to achieve what I want.

I have multiple datasets mapped to one y-axis in chart.js. This works well as we chart them to compare them across time (x-axis) and value. The y-axis expands based on all datasets.

I had a request to simply duplicate the labels so they show on both the left and right side. This does not seem to be simple as axes are mapped to datasets one-to-one.

Using https://stackoverflow.com/a/58525418/2060441 and updating it for my version of chart.js I came up with the below. Is there a better way? It feels very clunky. Notably once the chart options become an object, updating the min/max directly doesn’t appear to work so I have to replace it wholesale.

// add a dummy dataset, use legend.labels.filter to stop them showing
datasets.push({ yAxisID: 'yAxis2' });
            
forecast_chart.data.datasets = datasets;

minTick = forecast_chart.scales.yAxis1.min;
maxTick = forecast_chart.scales.yAxis1.max;

forecast_chart.options.scales.yAxis2 =
{
    type: 'linear',
    position: 'right',
    min: minTick,
    max: maxTick,
    ticks:
    {
        stepSize: 50,
    
    };
};
forecast_chart.update();
forecast_chart.resize();

Error 500 on Post Request using Mongoose Save Method

I established a model for Posts and created a POST request handler. As you can see, if it works, it will send a message back saying “nice” to the user who made the request.

Using Postman on desktop, I try to make a POST request with the necessary body, but it always arrives at a 500 error. Can someone explain why or is there something I’m missing?

const router = express.Router();
const Post = require('../models/Post')

router.get('/', (req, res) => {
  res.send('We are posts')
})

router.post('/', async (req,res) => {
  const post = new Post(req.body)

  try {
    await post.save();
    res.send("nice");
  } catch (error) {
    res.status(500).send("error");
  }
})



module.exports = router;

app.js

require ('dotenv/config')
const express = require('express');
const mongoose = require('mongoose')
const app = express();
const postsRoute = require('./routes/posts')

app.use(express.json())

app.use('/posts', postsRoute)

app.get('/', (req, res) => {
  res.send('We are home')
})

// Connect to DB
mongoose.connect(process.env.DB_CONNECTION,  {
  useNewUrlParser: true,
  useFindAndModify: false,
  useUnifiedTopology: true
},() => {
  console.log("connected to db")
})

I am using MongoDB Cloud, by the way.

Enable button if at least one checkbox is selected and with checkbox select all

I have a script that enables a button if at least one checkbox is selected and a checkbox selects all.

The problem is that I can’t make it work correctly, when I select the checkbox select all it activates the button but if I uncheck it it is not deactivating.

The delete checkboxes are working correctly the problem is in select all

var checa = document.querySelectorAll(".toggle");
var numElementos = checa.length;
var bt = document.getElementById("btn");
for(var x=0; x<numElementos; x++){
   checa[x].onclick = function(){
      // "input[name='toggle']:checked" conta os checkbox checados
      var cont = document.querySelectorAll(".toggle:checked").length;
      // ternário que verifica se há algum checado.
      // se não há, retorna 0 (false), logo desabilita o botão
      bt.disabled = cont ? false : true;
   }
}

//---------------------------------------

var roles = {
    checkall: {
        delete: true
    }
};

 $('.role').click(function() {
     var result = {};
     $('.role').each(function() {
         if (!$(this).prop('checked')) return;
         var role = $(this).attr('id');
         $.extend(result, roles[role]);
     });
     $('.perm').each(function() {
         var perm = $(this).attr('id');
         var chk = (perm in result);
         $(this).prop('checked', chk);
     });
 });
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container card m-4 p-3">

<div>
<input class="role toggle me-2" type="checkbox" name="toggle" id="checkall"/>Select all
</div>
<hr />
<div class="mb-1">
<input class="perm toggle me-2" type="checkbox" name="toggle" id="delete"/>Delete 1
</div>
<div class="mb-1">
<input class="perm toggle me-2" type="checkbox" name="toggle" id="delete"/>Delete 2
</div>
<div class="mb-1">
<input class="perm toggle me-2" type="checkbox" name="toggle" id="delete"/>Delete 3
</div>
<div class="mb-1">
<input class="perm toggle me-2" type="checkbox" name="toggle" id="delete"/>Delete 4
</div>
<div class="mb-1">
<input class="perm toggle me-2" type="checkbox" name="toggle" id="delete"/>Delete 5
</div>
<div class="mb-1">
<input class="perm toggle me-2" type="checkbox" name="toggle" id="delete"/>Delete 6
</div>
<hr />
<div>
    <button type="button" class="btn btn-danger btn-sm" id="btn" disabled> Delete selected</button> 
</div>
</div>

Error is thrown when reassigning new Error variable in NodeJs

I am using a package that is getting this error an I have figured out haw to reproduce it.

Basically assignment of a new Error() to a variable works, but then when you try to reassign it – it actually throws an error. Why does this happen?
Here is an example use case:

// Filename: test.js
var myError = new Error("Original Error.");

if (true) {
  myError = new Error("New Error!");
}

$ node test.js – executes no problem.

$ node
> .load test.js

^ This produces the error. However the package I am using does this similar pattern and gets the same error, but that is obviously not something I am doing in the node shell.

I have also found out that simply re-declaring the variable, instead of reassigning it will not invoke the error.

Any thoughts on this?

How to make prettier format style tags inside shadowDom.innerHTML in web components?

It seems running prettier ignores embedded style tags (and code) inside backticks:

import Base from './Base.js';

class NavBar extends Base {
    constructor() {
        super();
    }

    static get name() {
        return `${this.ns}-navbar`;
    }

    connectedCallback() {
        this.attachShadow({ mode: 'open' });
        this.shadowRoot.innerHTML = `
    <style>
      .navbar {
        margin-top: 1rem;
        display: flex;
        justify-content: center;
        align-items: flex-start;
      }
      
      .navbar a {
        margin: 0 .4rem;
        text-decoration: none;
      }    

        .navbar a.active {
            font-weight: 700;
            text-decoration: underline;
        }
    </style>
    <nav class="navbar">
        <a href="/recent.html" class="${this.isCurrentPage('/recent') ? 'active' : ''}">recent</a>
        <a href="/popular.html" class="${
                    this.isCurrentPage('/popular') ? 'active' : ''
                }">popular</a>
        <a href="/tags.html" class="${this.isCurrentPage('/tags') ? 'active' : ''}">tags</a>
        <a href="/" class="${this.isCurrentPage('/$') ? 'active' : ''}">home</a>
    </nav>
`;
    }
}

customElements.define(NavBar.name, NavBar);

.prettierrc:

{
    "useTabs": true,
    "singleQuote": true,
    "trailingComma": "none",
    "printWidth": 100,
    "arrowParens": "avoid"
}

Command: npx prettier -w .

Is there anyway to get prettier to format the code inside backticks?

Add Popup from Mapbox Studio Tileset in code HTML

I want to add popups (movemouse) from two Mapbox Studio tilesets to HTML code. This tileset are in the same map:
*Tileset 1: https://studio.mapbox.com/tilesets/mapanaval.1ogp366t/#10.95/-34.6229/-58.4428, atributes[Nombre, Tipo]
*Tileset 2: https://studio.mapbox.com/tilesets/mapanaval.5f95hcr9/#0.86/0/-58.4 , atributes[CALLE, TIPO]

¿What is the correct code to add popups to the next html?

https://raw.githubusercontent.com/datatto/Mapa-Naval/main/mapa_v1.html

Thanks!

Async/await in map function returning pending promise [duplicate]

I’m quite new to using async/await and am having some problems getting a function to work.
I have a function getRatings that maps through data returned from a call to my firebase firestore.
I’m wondering how I use async/await to return the data, because at the moment when I console.log the output of the function, I get

Promise {}

Here’s the function in question, filteredVenue represents the data returned from the firebase call:

  const getRatings = async () => {
    let arr = [];
    await filteredVenue.map((venue) => {
       return venue.reviews.map((ratings) => {
        const ratingsObject = {
          food: ratings.ratingFood,
          service: ratings.ratingService,
          value: ratings.ratingValue,
          atmosphere: ratings.ratingAtmosphere,
        };
        arr.push(ratingsObject);
      })
    })
    const newObject =  {
      food: arr[0].food,
      service: arr[0].service,
      value: arr[0].value,
      atmosphere: arr[0].atmosphere,
    };
    return newObject;
  };

  const venueRatings = getRatings() 

  console.log(venueRatings) // yields a pending promise

Any suggestions?