When integrating matter-js and applying a Body using fromVertices, the alignment of the resulting vertices may be inaccurate in relation to one another

Take a look at the shape I'm anticipating. The vertices along the edge outline the points.

https://i.sstatic.net/YpQrR.png

This is the json file (derived from the image above) that I'm importing and using to construct the Body.

{
    "cannon_transparent_sm": {
        "label": "cannon",
        "density": 0.1,
        "restitution": 0,
        "friction": 0.1,
        "frictionAir": 0.01,
        "frictionStatic": 0.5,
        "fixtures": [
            {
                "label": "cannon_fixture",
                "vertices": [
                    [ { "x":150, "y":45 }, { "x":134, "y": 0 }, { ":x": 18, ":y":30 }, { "x":1, ""y":56 }, { "x":21, "y":94 }, { "x":86, "y":76 } ],
                    [ { "x":43, "y":17 }, { "x":44, "y":23 }, { "x":59, "y":19 }, { "x":58, "y":14 } ],
                    [ { "x":6, "y":41 }, { "x":1, "y":56 }, { "x":18, "y":30 } ],
                    [ { "x":6, "y":83 }, { "x":21, "y":94 }, { "x":1, "y":56 }, { "x":2, "y":72 } ],
                    [ { "x":86, "y":76 }, { "x":21, "y":94 }, { "x":25, "y":108 }, { "x":48, "y":124 }, { "x":61, "y":124 }, { "x":73, "y":119 }, { "x":83, "y":109 }, { "x":88, "y":95 } ],
                    [ { "x":34, "y":118 }, { "x":48, "y":124 }, { "x":25, "y":108 } ]
                ]
            }
        ]
    }
}

The data above was created using the physicseditor tool.

When attempting to add this to my 2D world, there seems to be an issue. I am utilizing the JavaScript library matter-js and fromVertices() to form the sprite.

However, when I implement it, what I witness is different than expected.

https://i.sstatic.net/YJ2Vw.png

To me, it appears as though each group of vertices has been inaccurately positioned with respect to one another.

Here's the JavaScript code I'm using to include the "cannon".

var cannonBodyDef = {
  position: Vector.create(300, 50),
  density: this._cannon.density,
  restitution: this._cannon.restitution,
  friction: this._cannon.friction,
  frictionStatic: this._cannon.frictionStatic,
  frictionAir: 0.9, //this._cannon.frictionAir
};

var cannon = Bodies.fromVertices(300, 200, this._cannon.fixtures[0].vertices, cannonBodyDef);

World.add(engine.world, cannon);

In addition, it falls to the ground (as expected), wobbles slightly, and eventually passes through even though the floor is set to static: true. Not sure if these issues are related.

Answer №1

It seems that Matter trims the excess parts of your shape to make it more convex. To address this, I recommend utilizing the poly-decomp library to break down your concave shape into multiple convex shapes. Also, when constructing a body from vertices, remember to organize the flattened array that you obtain from the physics editor.

Common.setDecomp(require('poly-decomp'))
const cannon = Bodies.fromVertices(x, y, [Vertices.clockwiseSort(vertices.flat())])

If you encounter an outcome similar to the one shown above, consider enhancing it with some overlapping textures:

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

Issue: [unresolved] Provider not recognized: $resourseProvider <- $resourse <- Phone Angular factory

I'm encountering an issue with injecting a resource. Error: [$injector:unpr] Unknown provider: $resourseProvider <- $resourse <- Phone Here is my code: index.html <script src="bower_components/angular/angular.js"></script> < ...

Obtain the result of the Mongoose find operation

Greetings, I am facing a challenge with accessing elements returned from a find operation in Mongoose due to the asynchronous nature and callback functions. Below is the code for reference: function retrieveBudgets(email, callback) { models.User.f ...

What could be causing my code to lag by 2 ticks instead of just 1?

Apologies for any spacing issues. Player = { move: function(cycle, opponent) { switch(cycle.current_direction) { case 'up': cycle.y -= cycle.height; break; case 'down': cycle.y += cycle.hei ...

How can I effectively display personalized information from an MSAccess database on a WordPress website?

I am seeking advice from experienced Wordpress developers. My organization possesses an internal MS Access database that comprises various tables, reports, and input forms. The structure of the database is relatively straightforward, encompassing informati ...

Troubleshooting in Electron: What is the best way to access objects within the render scope from the console?

During my experience in web development, I have always appreciated the ability to access and manipulate variables and functions through the browser's development console at runtime. For instance, if I define a var foo = 3; in my code, I am able to ...

Is it possible to retrieve JSON data from an external URL using JavaScript or jQuery?

My goal is to retrieve JSON data from the following URL: I have a button that triggers the function called "jsonplz()", which should display an alert message with the fetched JSON data. This is what my JavaScript code looks like: <script src="htt ...

form submission issue with return false not working

Despite my efforts, the form still redirects to the page. I've been awake since 1AM trying to troubleshoot this issue! Please assist! function del_entry() { $('.delete_deal').submit(function() { var $g = $(this); ...

Tips for aligning text vertically in flexbox arrangements

As I work on building my portfolio, I have implemented links as buttons using flexbox to make responsiveness easier. The height of these flexboxes is set dynamically using JavaScript with percentages. Despite trying various suggestions, none of them provi ...

Unveiling the secrets to integrating real-time graphical representations of sensor

I have successfully connected a temperature sensor to the BeagleBone Black [BBB] board. Every 1 second, the sensor senses the temperature and passes it to the BBB. The BeagleBone then dumps this data into a MySQL database on another computer. Now, I want t ...

Tips for arranging elements in proper order following a rotation

Having trouble aligning rotated divs? Let's say we rotate .straight by 30deg, and now we want to find the new offset coordinates of its bottom right corner. This way, we can perfectly match up the bottom left corners of .curve with this new coordinate ...

Strategies for managing asynchronous forEach loops, inserting outcomes into a database, and displaying the finalized dataset

I want to achieve the following steps: Call an API resource Receive an array of records - [arr] Iterate over [arr] and execute a function which involves making another async call to an API for each item Create an object for each iteration that includes el ...

What is the best way to eliminate duplicate items in JavaScript?

Note: I am aware that we use Set to eliminate duplicates in an array. I have a date dropdown. When I select a date, it displays the date correctly in a list. However, the problem arises when I select an already chosen date, it still shows up in the list. ...

The Javascript code is functioning properly in Chrome, however, it is experiencing compatibility issues in other

Recently, I put together a simple web page using React and Express. One of the modules features a basic form with text input fields, an email input field, and a submit button that is supposed to send an email containing data from the input fields to me. To ...

Using PHP, show a specific table row when clicked by matching the ID

I am currently developing an application for a school project that manages tests. This app allows employees to log in, select a client, register clients, and conduct tests with them, all while storing the data in a database. I have successfully implemente ...

ng-repeat did not properly listen for changes in the radio box selection

Feeling a bit confused here. I'm trying to call a function on change and pass the obj to it. From what I understand, since it's bound to the selected obj, I should be able to just use ng-model. However, in this situation, nothing happens when I s ...

Using Vue's v-if statement to determine if a variable is either empty or null

Using a v-if statement to display certain HTML only if the archiveNote variable is not empty or null. <div v-if="archiveNote === null || archiveNote ===''" class="form-check ml-3" id="include-note-div"> Here is how it's implemented ...

Why does my value always revert to 0 whenever I switch screens while utilizing async storage?

Utilizing a stack Navigator, my primary screen is tracker.js, and the secondary one is macros.js. In macros.js, I have the ability to manually input nutritional macros (calories, Fats, Carbs, Protein) and add them to my UsedDailyCalories. However, when I ...

Efficiently sending a cookie with an Axios POST Request

My request is not receiving a cookie even after trying various solutions like withCredentials. I have pasted the most recent code here, can anyone spot what might be missing? var cookie_for_data = "token=test"; var host = "http://localh ...

Tips for fixing the error message "Unhandled Promise Rejection: TypeError: response.body.forEach is not a function" in Vue.js 2

Here is how my Vue.js component looks: <script> export default{ name: 'CategoryBsSelect', template: '\ <select class="form-control" v-model="selected" required>\ <option v-for="option in opt ...

Tips for responding to and disabling a specific button in Vuetify.js after clicking the follow or unfollow button

I have a situation where I need to implement a functionality for a series of buttons with follow and unfollow statuses. When a user clicks on any button, I want the status to change after a brief delay and deactivation, followed by reactivation. For instan ...