Updating the shape of an image's hitbox in Phaser 3: Instructions

Currently, I am working on developing a skateboarding game using the Phaser 3 framework in JavaScript. The challenge I'm facing is related to implementing a triangular hitbox for a ramp image I have loaded onto the screen. Initially, I used the "arcade" physics engine, but realized that to achieve a non-rectangular hitbox, I need to switch to the matter physics engine. However, integrating this with a triangular hitbox has been proving tricky.

I possess both the .png image file of the ramp and its corresponding .json hitbox file.

Despite attempting to follow a tutorial online regarding creating new hitboxes for the matter physics engine, my efforts resulted in everything falling off the screen. Additionally, I struggled with utilizing the .json file associated with the ramp.

// Physics engine configurations
var physicsConfig = {
    default: 'arcade',
    arcade : {
        debug : true  //TOGGLE TO TRUE FOR DEBUG LINES
    }
}

// Game setup
var config = {
    type: Phaser.AUTO,
    width: 1200 ,
    height: 600,
    physics: physicsConfig,
    scene: {
        preload: preload,
        create: create,
        update: update
    }   
}

// Initialize the game
var game = new Phaser.Game(config);

function preload() {
    // Loading images
    this.load.image('sky', 'archery_assets/images/sky.png');
    this.load.image('ground', 'skate_assets/images/ground.png');
    this.load.image('up_ramp', 'skate_assets/images/up_ramp.png')

    // Spritesheets
    this.load.spritesheet('player', 'skate_assets/spritesheets/skater.png', {frameWidth: 160, frameHeight: 160});

}

function create() {
    // Background setup
    skyImg = this.add.image(600, 300, 'sky');
    skyImg.setDisplaySize(1200, 600);
    groundImg = this.add.image(600, 600, 'ground');
    groundImg.setDisplaySize(1200, 250);

    // Player creation
    this.player = this.physics.add.sprite(100, 410, 'player');
    this.player.setCollideWorldBounds(true);

    // Animation setup
    this.anims.create({
        key: 'move',
        frames: this.anims.generateFrameNumbers('player', {start: 0, end: 3}),
        frameRate: 16,
        repeat: -1 
    });
    
    this.anims.create({
        key: 'push',
        frames: this.anims.generateFrameNumbers('player', {start: 4, end: 8}),
        frameRate: 16
        
    });

    this.player.anims.play('move', true);

    // Up ramp properties
    this.upRamp = this.physics.add.sprite(700, 330, 'up_ramp');
    this.upRamp.setSize(320, 150).setOffset(0, 175);
    this.upRamp.enableBody = true;
    this.upRamp.setImmovable();
    this.upRamp.body.angle = 150;

    // Input setup
    this.cursors = this.input.keyboard.createCursorKeys();

    this.spacebar = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);

    this.physics.add.collider(this.player, this.upRamp);
}


function update() {

    var playerPushSpeed = 0;

    if (this.spacebar.isDown) {
        
        this.player.anims.play('push', true);

        playerPushSpeed += 175;
        
        this.player.setVelocityX(playerPushSpeed);   
    }

    if (this.upRamp.body.touching.left) {
        this.player.setVelocityY(-200);
    }
}

The main hurdle lies in figuring out how to incorporate the .png ramp image in conjunction with its respective .json hitbox file, enabling the player to smoothly traverse the ramp as intended.

Answer №1

If you want to modify the shape of the hitbox, you'll need to utilize the physics: { default: 'matter' }. Take a look at this snippet of code for guidance:

var config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    backgroundColor: '#000000',
    parent: 'phaser-example',
    physics: {
        default: 'matter',
        matter: {
            gravity: {
                y: 0
            },
            debug: true
        }
    },
    scene: {
        create: create
    }
};

var game = new Phaser.Game(config);

function create ()
{
    this.matter.world.setBounds();

    this.matter.add.rectangle(200, 200, 200, 200, { 
        chamfer: { radius: [230, 0, 200, 0 ] }
    });

    this.matter.add.mouseSpring();
}

You can also use a PhysicsEditor tool and follow this helpful tutorial on implementing various shapes.

EDIT:

To explore other available shapes for implementation, try using console.log(this.matter.bodies).

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

What is the method for showcasing background images sequentially?

css code #intro { position: relative; background-attachment: fixed; background-repeat: no-repeat; background-position: center top; -webkit-background-size: cover; -moz-background-size: cover; backgr ...

Angular.js enables seamless synchronization between contenteditable elements and the $scope object by automatically updating the

I'm completely new to Angular.js and have been exploring various tutorials to grasp the concept of two-way binding with contenteditable elements within an ng-repeat. Currently, I am utilizing a shared 'store' between controllers like this: ...

Step-by-step guide to utilizing instance functions in AngularJS

Recently I started working with angular in my project but I'm struggling to figure out how to access instance functions from the original code. Here is a snippet of my function: $scope.collapsedrow = true; $scope.PlusClick = function(event) ...

What is the best way to show a pop-up modal in Vue.js?

Having some trouble getting the Vue Modal to work in my Vue-cli setup for reasons unknown. Attempting to implement the modal example from: https://v2.vuejs.org/v2/examples/modal.html I'm still fairly new to Vue, so bear with me and my basic question. ...

Customizable positioning of hover messages while ensuring messages do not extend past the boundaries of the object

Within an application featuring a dynamic assortment of plots rendered and scaled within a fixed div, I am grappling with the final scenario whereby, in a layout of plots spanning multiple columns and rows, the message should be contained within the groupi ...

When the Promise object is assigned to the img [src], the image may occasionally be set to null

I incorporate Angular into my Electron application. One of the components in my app contains an array called files, where each element is an object with a member named preview. This preview member is a Promise object that returns a file:// object. <mat- ...

AngularJS radio buttons are unable to be selected in a simplistic manner

I have implemented a dynamic list display using HTML radio buttons. Here is the code snippet: <html> <head> <script src="angular-v1.5.5.js"></script> </head> <body> <div ng-app="myApp" ng-controller=" ...

Issues with visuals in jQuery.animate

I have nearly finished implementing a slide down drawer using jQuery. The functionality I am working on involves expanding the drawer downwards to reveal its content when the handle labeled "show" is clicked, and then sliding the drawer back up when the ha ...

I recently implemented a delete function in my code that successfully removes a row, but now I am looking to also delete the corresponding data from localStorage in JavaScript

I have successfully implemented a delete function in JavaScript that deletes rows, but I also want to remove the data from local storage. This way, when a user reloads the page, the deleted row will not appear. The goal is to delete the data from local s ...

Using JavaScript to detect the Facebook like button on a webpage

I am currently developing an application for Facebook using HTML and Javascript. My goal is to be able to detect when a user clicks the "Like" button on my company's Facebook page without needing to embed a separate "Like" button within my app itself. ...

PHP Proxy - Sending Files using cURL

I am in the process of developing an application using AngularJS for the frontend and a Laravel-based API for the backend. To maintain security, I pass data through a PHP proxy before reaching the API. When it comes to POST requests, the proxy decodes the ...

What could be the reason behind jQuery.ajax not being able to return JSON data within a loop

I am currently attempting to iterate through an array in JavaScript with array values appended to the end of a variable named "url" in order to retrieve the corresponding JSON data from a website. However, it seems to be returning an error message: {"Error ...

Localhost is experiencing issues with loading an Angular 6 app

I have created an app on stackblitz that functions perfectly in their web environment. However, when I download the project and attempt to run it on my own machine, it gets stuck on 'loading'. Despite installing all necessary npm modules, includ ...

Turning away swiftly from a popover triggered by hovering does not automatically conceal the popover

When utilizing hover-triggered popovers for specific highlighted rows within a table, I noticed an issue. If you scroll away quickly using the mouse wheel, the popover remains visible for an extra second even though you are no longer hovering over the targ ...

What is the best method for utilizing dynamically assigned keys within a JSON object?

I am currently working with Rhino and I need to find a way to utilize a variable in order to define the key of a map. Here's an example of what I'm trying to achieve: var name = "Ryan"; var relationshipType = "brother"; var relatedName = "David" ...

Having trouble with the Slide Menu Javascript functionality

Having some trouble creating a sliding menu with jQuery. Errors on lines 5 and 6 saying functions are not defined. Can anyone help me figure out what's wrong with my code? jQuery(function($) { "use strict"; $(document).ready(function () { ...

Idea for a New Web Chat Feature

Hey there, I've been considering adding a shoutbox to my website. However, I'm looking for a solution that will seamlessly integrate with my existing members database. I have some ideas in mind but I'm not entirely sure of the best approach. ...

Testing an Angular Controller that incorporates Kendo Grid and Datasource functionality

Currently, my project is utilizing AngularJS along with Kendo-UI. I am facing an issue while attempting to test one of my Controllers that incorporates a Kendo-UI Grid: angular.module('myApp')('DevicesCtrl', function ($scope) { $s ...

I need a counter in my React application that is triggered only once when the page scrolls to a specific element

I've encountered a challenge with a scroll-triggered counter on a specific part of the page. I'm seeking a solution using React or pure JavaScript, as opposed to jQuery. Although I initially implemented it with states and React hooks, I've ...

Displaying a div on the click of an image within a for loop using JavaScript

Currently, my website has a blog page that only showcases each individual blog post's photo and title. This is achieved through the use of a FOR loop (shown below). I am interested in implementing a feature where clicking on a blog post's photo o ...