rectangle 2d collision detection and response that works with corners

I’m making a 2d game, and I’ve been struggling a lot with 2d collision. I have code that seems to work fine except for corners. When an entity collides exactly with a corner it just end up going straight though.

I’ve been trying to fix for literally 3 weeks. Ive tried AI, I’ve tried documentation, yt tutorials (which is where i got the code i have now) but nothing seems to work for corners as well.

Here is my current code:

for (let i = 0; i < entityHitboxLength; i += 8) {
        let entityX = entityHitboxes[i];
        let entityY = entityHitboxes[i + 1];
        let entityXW = entityHitboxes[i + 2];
        let entityYH = entityHitboxes[i + 3];
        let prevEntityX = entityHitboxes[i + 4];
        let prevEntityY = entityHitboxes[i + 5]; 
        let prevEntityXW = entityHitboxes[i + 6];
        let prevEntityYH = entityHitboxes[i + 7];

        if (
          selfYH > entityY &&
          selfY < entityYH &&
          selfX < entityXW &&
          selfXW > entityX
        ) {
          if (selfYH >= entityY && prevSelfYH < prevEntityY) {
            selfYH = entityY - 1;
            selfY = entityY - 1 - height;
          } else if (selfY <= entityYH && prevSelfY > prevEntityYH) {
            selfY = entityYH + 1;
            selfYH = entityYH + 1 + height;
          }
          else if (selfXW >= entityX && prevSelfXW < prevEntityX) {
            selfXW = entityX - 1;
            selfX = entityX - 1 - width;
          } else if (selfX <= entityXW && prevSelfX > prevEntityXW) {
            selfX = entityXW + 1;
            selfXW = entityXW + 1 + width;
          }
        }
      }

Here is the code documentation i used for this.

Pretty simple and it works fine for edges.
Ive also tried an AI generated approach like

if (
  selfYH > entityY &&
  selfY < entityYH &&
  selfX < entityXW &&
  selfXW > entityX
) {
  // Calculate overlaps on both axes
  const overlapY = Math.min(selfYH - entityY, entityYH - selfY);
  const overlapX = Math.min(selfXW - entityX, entityXW - selfX);

  // Resolve the smaller overlap first
  if (overlapX < overlapY) {
    // Resolve X-axis collision
    if (selfXW >= entityX && prevSelfXW < prevEntityX) {
      selfXW = entityX - 1;
      selfX = entityX - 1 - width;
    } else if (selfX <= entityXW && prevSelfX > prevEntityXW) {
      selfX = entityXW + 1;
      selfXW = entityXW + 1 + width;
    }
  } else {
    // Resolve Y-axis collision
    if (selfYH >= entityY && prevSelfYH < prevEntityY) {
      selfYH = entityY - 1;
      selfY = entityY - 1 - height;
    } else if (selfY <= entityYH && prevSelfY > prevEntityYH) {
      selfY = entityYH + 1;
      selfYH = entityYH + 1 + height;
    }
  }
}

But this passes through even more than the one im using, even at corners still. Is there something wrong with this code? how can i make it work?

converting multiple connecting polygon’s to 1 polygon

I am building a floor planner app (react/typescript), currently I have all walls as polygon where we define 4 corners.

I need a logic/algorithm to merge connecting walls. I did try convex/concave hull and variations, but nothing seems to work as I need.

enter image description here

Here on the left side we have my walls as I draw them with polygons, and on the right side what I need.

export type Location = {
  x: number;
  y: number;
};

export type Size = {
  length: number;
  thickness: number;
};

export type Corners = { // corner 1, 2, 3, 4 are the polygon locations for the wall
  c1: Location;
  c2: Location;
  c3: Location;
  c4: Location;
  c5: number;
  c6?: Location;
};

export type PlanObject = { // wall
  index: number;
  toolType: number; // tooltype
  wallType?: number;
  text?: string;
  orientation: number; // will always be angle
  corners: Corners;
  location: Location;
  size: Size;
  internal: boolean;
};

I could add all 5 different ways I tried to fix this, but none are working and not sure if any of these would be the correct way to continue.

anyone that could point me to the correct way would be awesome.

how to repeat async function javascript

I am trying to make a slider, but can not figure out how to repeat function d() x number of times:

<script>
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
};
async function d() {
    var a = document.getElementsByClassName('sliderimage').length;
    var g = document.getElementsByClassName('sliderimage');
    for (var c = 0; c<a; c++) { 
    g[c].style.display = 'block';
    await sleep(2000);
    g[c].style.display = 'none'; 
};};
d();
</script>

I have tried adding a loop around my function, but does not work.

bot and/or terminal not processing message.startsWith(‘goto’) on my mineflayer bot

I wanted to make the bot go to a specific coordinate I inputted in the minecraft chat, something along the lines of ‘goto x y z’ and it goes to said x, y, and z coordinates. Yet it isn’t picked up by the bot.

bot.on('path_update', (r) => {
    console.log('Goal updated');
  });
  bot.on('goal_reached', (goal) => {
    console.log('Here I am');
  });

else if (message.startsWith('goto')) {
      const cmd = message.split('');

      if (cmd.length === 4) {
        const x = parseInt(cmd[1], 10);
        const y = parseInt(cmd[2], 10);
        const z = parseInt(cmd[3], 10);

        bot.pathfinder.setMovements(DefaultMove);
        bot.pathfinder.setGoal(new GoalBlock(x, y, z));
      } else if (cmd.length === 3) {
        const x = parseInt(cmd[1], 10);
        const z = parseInt(cmd[3], 10);

        bot.pathfinder.setMovements(DefaultMove);
        bot.pathfinder.setGoal(new GoalXZ(x, z));
      } else if (cmd.length === 2) {
        const y = parseInt(cmd[1], 10);

        bot.pathfinder.setMovements(DefaultMove);
        bot.pathfinder.setGoal(new GoalY(y));
      }
    }

Here’s a snippet of the ‘goto’ event where if I type ‘goto [x] [y] [z]’ I want the bot to go to that specific coordinate in the minecraft world.

However, when I do attempt the event, it didn’t even register in the terminal, which leads me to suspect that theres something wrong with this part of the code.

else if (message.startsWith('goto'))

I know this because I added a bot.on(‘path_update’) which supposedly replies ‘Goal updated’ on the terminal, yet when I do input the command on my minecraft world, the terminal returned nothing, hence why I think it’s the bot not picking up the command

I’ve tried searching and even copy-pasting the actual code from the mineflayer-pathfinder github page itself, yet it still doesnt work

Here’s a video of me replicating the problem
https://imgur.com/a/IFb1gak

Is there a way in array.map() method to access / iterate the keys of multiple key/value-pairs per index (not the index)

Is there a way in the array.map() method to access / iterate the keys for every key/value-pair in each index?

In NodeJS Express I receive the following data in req.body from a POST-request:

[
   { ptiid: '2', ptiname: 'PTI26-Profile-1', order: '1', size: 25 },
   { ptiid: '5', ptiname: 'PTI29-Profile-1', order: '2', size: 25 },
   { ptiid: '3', ptiname: 'PTI27-Profile-1', order: '3', size: 25 },
   { ptiid: '4', ptiname: 'PTI28-Profile-1', order: '4', size: 25 }
]

The goal is to find out whether I could use .map() to shorten my route-files in general.
Up to this point I have been using FOR OF loops (for multi row requests because of await) and manual declarations of variables, in order to prepare the MYSQL Query:

let ptiId = req.body.ptiid
let ptiName = req.body.ptiname
// and so on...

The clean and concise look of .map() appeals to me here.
I would like to prepare my MYSQL-Query-Variables accordingly and wonder if I can access the keys:

let elements = req.body //possibly just chaining .map() to req.body directly later

let sqlVars = elements.map(element => {
   console.log(`The value ${element.ptiid} is easy to get if I know the key`)
   console.log(`If only I could get a key like ${element.key}, then I could call all values by their keys`)    
})

Please just let me know if this is not possible – then I just abandon the idea. If the suggested code is too long, I would probably not use it – but it would still be good to learn.

How to Implement an EventBus for a TypeScript-Based CLI Framework (climonad.js)?

I’m currently developing a CLI framework called climonad.js — which is written in TypeScript — and I’d like to introduce an Event Bus mechanism to handle and dispatch various events (e.g., errors, command lifecycle notifications, usage tracking). My goal is to decouple these concerns so that other modules can listen for and respond to events without relying on Node.js – specific modules (like the built-in “events” package).

Below is a short concept of the kind of EventBus I was thinking:

export class EventBus {
  private listeners: Record<string, Array<(...args: unknown[]) => void>> = {}

  /**
   * Register an event listener for a specified event.
   */
  public on(event: string, listener: (...args: unknown[]) => void): void {
    if (!this.listeners[event]) {
      this.listeners[event] = []
    }
    this.listeners[event].push(listener)
  }

  /**
   * Unregister an event listener.
   */
  public off(event: string, listener: (...args: unknown[]) => void): void {
    if (this.listeners[event]) {
      this.listeners[event] = this.listeners[event].filter(l => l !== listener)
    }
  }

  /**
   * Emit an event to all registered listeners.
   */
  public emit(event: string, ...args: unknown[]): void {
    if (this.listeners[event]) {
      for (const listener of this.listeners[event]) {
        listener(...args)
      }
    }
  }
}

Example usage might look like this:

import { EventBus } from "./EventBus"

const bus = new EventBus()

// Subscribe to an "error" event
bus.on("error", (err: unknown) => {
  console.error("[climonad.js] Error:", err)
})

// Emit the error somewhere else in the code
try {
  // Some CLI-specific action...
} catch (e) {
  bus.emit("error", e)
}

I’m hoping to get feedback on the following points:

  1. Is there a more idiomatic or recommended approach to implementing a pub/sub or event-based architecture in a TypeScript CLI project?
  2. Do you see any pitfalls in this simplistic design (like potential memory leaks or performance issues) if the CLI grows large or is run frequently?
  3. Would you suggest introducing any kind of priority handling or asynchronous event processing for more advanced CLI tasks?
  4. Are there known patterns for bridging event emissions between different modules (e.g., usage tracking, error logging) in a CLI context that I should look into?

I’d love to hear your suggestions, best practices, or potential improvements. Thanks in advance!

Related issue: https://github.com/supitsdu/climonad.js/issues/23

puppeter click method not work for mobile device toolbar

when i use click method in normal browser screen_resolution then it is work but when i set in mobile device mode with the help of browser mobile screen toolbar then this method not work

screenshot when webpage open in mobile device view

const delay = async (ms) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
};

async function performAutomation(websocketUrl, targetUrl) {
  const browser = await puppeteer.connect({ browserWSEndpoint: websocketUrl });

  const pages = await browser.pages();
  const page = pages[0];
  await page.goto(targetUrl);
  const selector = "#answer-buttons > button:nth-child(1)";
  await page.click(selector)
  await delay(30000);

  setTimeout(async () => {
    await browser.close();
  }, 5000);
}

Centering a div vertically when using shape-outside

I’m trying to achieve this effect where the text wraps the outline of the image, but is also centred

The problem is that afaik to use shape-outside: url() to wrap the text I need to float the image, which means the parent cannot be flex or grid. That’s making centering the items vertically difficult.

I’ve tried using top: 50% and then translating y by -50%, but that doesn’t translate the shape path that the text wraps around.

top seems to have no effect, and other suggestions like display:table and vertical-align:middle break the float that’s needed.

Just a bit stuck. Would prefer css only, but happy with js if needed. Any help would be appreciated!

What I’m after:

enter image description here

What I’ve currently got:

enter image description here

.shape-outside {
  shape-outside: url(https://9gdz2scbii.ufs.sh/f/zWQ2Yd3CAlqfqpqn7xOJVXdr2TwsUaM9xB8kENtWjbYcPCoz);
  shape-margin: 25px;
  display: flow-root;
}
<script src="https://cdn.tailwindcss.com"></script>


<div class="wrapper">
  <section class="relative flow-root w-3/4 border border-red-500 mx-auto ">
    
    <img class="shape-outside w-[70%] float-right" src="https://9gdz2scbii.ufs.sh/f/zWQ2Yd3CAlqfqpqn7xOJVXdr2TwsUaM9xB8kENtWjbYcPCoz" alt="">
    
    <div class="relative border ">a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a 
    </div>

  </section>
</div>

Module parse failed: Unexpected token (8:2)

I made a React App 4-5 years ago, I’ve been trying to run but to no avail, I have tried solutions listed in other questions asked about similar problem, rn I’m totally confused with this and not sure what to do to get it running, I’m happy to provide all the required details in short notice.

This is the error I am getting when running npm start

ERROR in ./src/index.js 8:2
Module parse failed: Unexpected token (8:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| ReactDOM.render(
<React.StrictMode>
|
| </React.StrictMode>,

webpack 5.97.1 compiled with 1 error in 286 ms

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

/* const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
); */

reportWebVitals();

WebPack Config file

import { resolve as _resolve, join } from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';

export const entry = './src/index.js';
export const output = {
  path: _resolve(__dirname, 'dist'),
  filename: 'bundle.js',
};
export const module = {
  rules: [
    {
       test: /.(js|jsx)$/,
       exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        
      },
    },
  ],
};
export const resolve = {
  extensions: ['.js', '.jsx'],
};
export const plugins = [
  new HtmlWebpackPlugin({
    template: './public/index.html',
  }),
];
export const devServer = {
  static: join(__dirname, 'public'),
  compress: true,
  port: 3000,
};

AR.JS / Aframe – Multiple custom markers not working correctly

Bug:

Currently I have setup an AR.JS project with two different custom patterns, each showing a different 3D object (blue and red cubes). When I use AR, both patterns show the same cube and it is not working correctly.

Expected:

I would see a red cube for one pattern and a blue cube for the other pattern.

Note:

I have tested this with both of the default markers (kanji and hiro), and both work correctly so the issue seems to be with custom markers.

Code:

<!DOCTYPE html>
<html>
  <head>
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=Pixelify+Sans&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="style.css" />
    <script src="script.js" defer></script>
  </head>
  <script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script>
  <!-- we import arjs version without NFT but with marker + location based support -->
  <script src="https://raw.githack.com/AR-js-org/AR.js/master/aframe/build/aframe-ar.js"></script>
  <body>
    <a-scene embedded arjs vr-mode-ui="enabled: false">
      <a-marker
        preset="custom"
        type="pattern"
        url="patterns/pattern-01000110.patt"
        registerevents
      >
        <a-entity
          material="color: blue"
          geometry="primitive: box"
          scale="0.5 0.5 0.5"
          position="0 0 0"
        ></a-entity>
      </a-marker>
      <a-marker
        preset="custom"
        type="pattern"
        url="patterns/pattern-01000101.patt"
        registerevents
      >
        <a-entity
          material="color: red"
          geometry="primitive: box"
          scale="0.5 0.5 0.5"
          position="0 0 0"
        ></a-entity>
      </a-marker>
      <a-entity camera></a-entity>
    </a-scene>
  </body>
</html>

Any help would be appreciated, thanks.

Is it possible to upload image file to server using quilljs?

Good afternoon,Is it possible to upload image file to server using quilljs?
can someone tell me how to send images to the server using quilljs.

I tried that way but I was not successful.

<!DOCTYPE html>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/quill.snow.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/quill.js"></script>
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css"
/>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css" />

<div id="editor">
</div>

<!-- Initialize Quill editor -->
<script>
  const toolbarOptions = [
  ['bold', 'italic', 'underline'],
  ['blockquote'],
  ['image', 'video',],
                                      
];

const quill = new Quill('#editor', {
  modules: {
    toolbar: toolbarOptions
  },
  theme: 'snow'
});
  
  
 

function selectLocalImage() {
    var input = document.createElement("input");
    input.setAttribute("type", "file");
    input.click();
    // Listen upload local image and save to server
    input.onchange = () => {
        const file = input.files[0];
        // file type is only image.
        if (/^image//.test(file.type)) {
            this.saveToServer(file, "image");
        } else {
            console.warn("Only images can be uploaded here.");
        }
    };
}

function saveToServer(file) {
    const fd = new FormData();
      fd.append('image', file);

      const xhr = new XMLHttpRequest();
      xhr.open('POST', 'https://localhost/imagens', true);
      xhr.onload = () => {
        if (xhr.status === 200) {
          // this is callback data: url
          const url = JSON.parse(xhr.responseText).data;
          insertToEditor(url);
        }
      };
      xhr.send(fd);
}
function insertToEditor(url) {
    // push image url to editor.
    const range = quill.getSelection();
    quill.insertEmbed(range.index, "image", url);
}
   
  
  quill.getModule("toolbar").addHandler("image", () => {
        this.selectLocalImage();
    });
</script>

I get response 301 on console

Could someone help me fix it?

I am deeply grateful, just study objectives for a beginner.

CSS or js trick to arrange from items on a canvas

I have a set of from items, all wrapped in div on a canvas.

<div id="canvas">

    <div>
    <input type = "text"/>
    </div>

    <!-- other divs ... -->

</div>

We know the top, left, width and height of all these. However, these items are placed on the canvas by mouse dragging, i.e. manually. Therefore, the alignment is imperfect.

What I want, is a simple way, to align and arrange them.
Example:

enter image description here

should become:

enter image description here

See how the left top and right elements are aligned at the top…

If an item has place to grow to the right, it should be allowed to grow.

More example:

enter image description here

Should become:

enter image description here

See the Blue item is shrunk. and the yellow item is raised. This is decided, because the shrinking would be a smaller change, than growing it to take the entire horizontal space and would create a large gap between the pink element and the blue one, like this:

enter image description here

Also, the result would be less compact. This should have a lower priority. I understand some solution may end up like this in any case – but that should be the last resort.

Attempt to solution:
I have tried to use grid layout in css and find the nearest grid column/row. But that is resulting in unpredicted behavior.

I would prefer a simple solution that i can implement in valina js + jquery, ideally, a library that i can include, and call a function.

I understand that writing a full layout algorithm will be very complex. So before i re-invent the wheel, my question is:

Is there a simple solution to this using CSS/JS without using node/react or other frameworks? Thank you

d3 Many-To-Many Tree(?) with set y value

I’m relatively new to using d3 – though I’m currently trying to work with d3 v7 if that helps. What would be the best way to draw a graph like this? (With many more nodes) I’m currently planning on working with a number nodes and links, with the displayed example with a data structure of something like this,

nodes = [{‘name’: ‘1A’, level: 1},{‘name’: ‘1B’, level: 1},{‘name’: ‘2A’, level: 2},{‘name’: ‘2B’}…]

links = [{‘source’: ‘1A’, ‘target’ :’2A’}, {‘source’: ‘1A’, target: ‘3B’}…]

enter image description here

As you can see with the chart I’ve randomly drawn up, the lines will start to get confusing very quickly.

I’m also not sure if there’s a recommended algorithm to sort this at all.

During my testing, I created a base tree (where there’s only 1 parent for each leaf, but multiple children), but I generated the children recursively from each parent, which is how I grouped them together. This was mainly for testing, and it doesn’t utilize any of the d3 methods out there (more of a proof-of-concept for myself) but I wasn’t sure how to implement something similar with

how to handle signals in a deno 2 child process

Using Deno 2.1.5 in Windows 11, I have a script, which creates a subprocess, using the Deno.Command class (without the ‘piped’ option on stdin, stdout or stderr), then calling .output() on the resulting object. In simple cases, that works great. But now I want the child process to watch for and react to file changes. The only way I know to stop the watcher is to use Ctrl-C. But I want the Ctrl-C to only terminate the child process, not the main process that spawned it.

What I don’t know is exactly where the Ctrl-C goes. Does it go to the child process (which is what I expected), the parent process or both? I know that I can use Deno.addSignalListener("SIGINT", sigIntHandler); to set up a signal handler, but when I do that in the parent process so it will ignore Ctrl-C, it prevents the child process from terminating on Ctrl-C.

Infinite loop when using useDebounce

I making a project in React that I need to fill a form and then send what was answered into my DB, to do so I was wanting to use the hook useDebounce to send the submition after the user stop the interaction. But when I tried to do so it results in a infinite loop and I don’t know how to implement it.

This is my code review:

First I have my hook that have all the operations from that entity using GraphQL:

// useRecommendation.js
  ...
// other operations

export const useUpdate = () => {
  const [updateCriteria, { loading, error }] = useMutation(UPDATE_CRITERIA);
  const update = { handle: updateCriteria, loading, error };

  return update;
};

Then I import all operations into a object making like a model:

// Recommendation.js
const Recommendation = {
  all: useGetAll,
  byCategory: useGetByCategory,
  create: useCreate,
  update: useUpdate
}

export default Recommendation

And then I’m importing this entity in my component handler:

export const useRecommendationFormHandler = ({ form }) => {
  const updateRecommendation = Criteria.update();

  const submitRecommendation = async () => {
    try {
      const { data } = await updateRecommendation.handle({
        variables: {
          input: {
            conformity: form.conformity,
            importance: form.importance,
            comment: form.comment,
            conclusion: form.conformity === 0 && form.importance !== null,
          },
          criteria_id: form.id
        }
      });

      return data;
    } catch (error) {
      console.error("Erro ao atualizar a criteria", error);
    }
  };

  return {
    isLoading: updateRecommendation.loading
  }
};

I think it is important to say that the component that I’m trying to use the useDebounce is being rendered within a loop:

      <Grid sx={{ paddingX: 3 }}>
        {forms.length !== 0 && criterias.data.map((data, i) => (
            <RecommendationForm 
              key={data.id} 
              recommendation={data.recommendation.description}
              form={forms.find(f => f.id === data.id)}
              onChange={handleChange}
              index={i}
              onRefetch={onRefetch} 
            />
          ))
        }
      </Grid>

What can I do to send the answers to my db using this hook?

Edit:
I was using the useDebounce like this:

  const debouncedForm = useDebounce(form, 1000);
  const updateRecommendation = Criteria.update();

  const submitRecommendation = useCallback(async () => {
    try {
      const { data } = await updateRecommendation.handle({
        variables: {
          input: {
            conformity: debouncedForm.conformity,
            importance: debouncedForm.importance,
            comment: debouncedForm.comment,
            conclusion: debouncedForm.conformity === 0 && debouncedForm.importance !== null,
          },
          criteria_id: debouncedForm.id
        }
      });

      return data;
    } catch (error) {
      console.error("Erro ao atualizar a criteria", error);
    }
  }, [debouncedForm, updateRecommendation]);

  useEffect(() => {
    if (debouncedForm) {
      submitRecommendation()
    }
  }, [debouncedForm, submitRecommendation])