How to create a gelatin-like effect on a rectangle using HTML5 canvas

Currently, I'm working on a platformer game project in JavaScript. The concept involves players as rectangles jumping on and off platforms. While the basic functionality is set up, I'm now aiming to incorporate a unique 'gelatine effect' to the gameplay. This effect would make the player rectangles behave like gelatine upon landing on platforms. Despite my efforts to find examples or resources on how to dynamically change the shape of a rectangle element, I've hit a roadblock.

One approach I experimented with was using CSS @keyframes for animation, which worked when applied directly to HTML elements. However, implementing this effect on programmatically created player objects proved challenging due to limited access to CSSStyleDeclaration properties.

I am uncertain about converting the CSS animation keyframes to JavaScript or exploring alternative methods to achieve the desired outcome. Would appreciate any insights or guidance if there are better ways to implement the gelatine effect in my platformer game?

Answer №1

Jelly.

To achieve a jelly effect for use in a game, we can utilize a step-based effect that is open-ended (meaning the duration of the effect depends on the environment and has no set time limit).

Jelly and most liquids exhibit the property of being incompressible, meaning their volume does not change regardless of the applied force. In a 2D game, this implies that the area of jelly remains constant even when squashed vertically, allowing us to calculate the width based on the known area.

When an object falls and hits the ground, we can apply a squashing force vertically to simulate a damped spring effect, resulting in a very realistic jelly-like behavior.

Defining the jelly

In a playful manner fitting the season, I've defined two variables - 'wobbla' and 'bouncy', representing the stiffness and damping of the spring respectively. 'Wobbla' ranges from 0 to 1, with 0.1 being very soft and 1 being rigid, while 'Bouncy' ranges from 0 (full damping) to 1 (no damping). Additionally, there's a 'react' multiplier to amplify the spring force for exaggerated effects in the game.

'hr' and 'hd' (misleading names indeed!) denote the displayed height and the per-frame change in height, controlling the spring effect.

Moreover, flags indicate whether the jelly is on the ground and if it should stick to it ('sticky' flag) or bounce off it.

Three functions are available to manipulate the jelly:


function createJellyBox(image,x, y, wobbla, bouncy, react){
    return {
        img:image,
        // other properties...
    }
}

The functions

Three functions - reset, update, and draw - govern the jelly's behavior, but they surpass the character limit. You can find these functions in the demo below.

Draw

This function visually represents the jelly by adjusting its height and calculating the corresponding width before drawing the image at the center position for simplicity.

Reset

A straightforward function that resets the jelly's position at specified coordinates, eliminating any wobbles by setting 'jelly.hr = jelly.h' and 'jelly.hd = 0'.

Update

This function handles the core mechanics of the jelly, incorporating gravity, impact detection, force application, and ensuring the jelly doesn't intersect the ground. It also enhances the smoothness of the wobbly effect over time.

Understanding these details might require some effort, so feel free to ask questions for clarification.

DEMO

No comprehensive answer is complete without a demo! The jelly simulation supports interactive control using sliders and options like sticky mode. Experiment with the settings and observe how they influence the jelly effect. Responsive design ensures functionality across various screen sizes, providing an engaging user experience.

Note: The demo includes UI elements and additional code for user interaction, clearly distinguishing the answer code within the main loop section. If encountering any issues, especially on FireFox, do let me know for possible refinements.

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

Instant urban locator

Is there a way to automatically populate the visitor's city in the membership form? Member Register Form Name: Emre Email:--- Pass:--- City: Istanbul // Automatically detected location How can I implement automatic location detection for the ...

Implementing a delegator with ExtJS 4.1: A step-by-step guide

As a newcomer to javascript, I've recently been tasked with maintaining an application built in Sencha ExtJS 4. One of the components I need to modify is a tooltip feature that displays information when hovering over certain elements. This tooltip app ...

Unable to access GDrive on Moodle with an iOS device

I have an iframe code that works in Android, but not on iOS when embedded in Moodle. Does anyone know how to fix this issue? <p><iframe src="https://drive.google.com/embeddedfolderview?id=1d-SHXhof2KnyTmMr2GowJuf4bVKFKQg3&amp;usp#list&q ...

securing data with javascript object encryption

let User = {}; User.username = e.row.username; User.email = e.row.email; User.password = e.row.password; Here is my user object, which I want to store in a file. But before saving it, I need to encrypt the data for security reasons. When reading the file, ...

Discovering the compiled CSS file in React when using Sass: A step-by-step guide

In my React project, I have incorporated SASS. Now I am looking to find the final compiled CSS file from that SASS code. Whenever I navigate to: While there is the SCSS file visible, where can I locate the CSS version? I am referring to the compiled outp ...

I encountered an error in the console stating, "Uncaught ReferenceError: req is not defined," while trying to access req.query.id

Encountering the error 'Uncaught ReferenceError: req is not defined' when attempting to use req.query.id. Below is the content of my index.js file: const express = require("express"); const path = require("path"); const port = 8000; ...

What could be causing my Vue.js sorting array script to malfunction?

I'm encountering an issue with sorting the table by Date. The sort function used to determine the type of sorting no longer works, and I'm unsure why. html: <th @click = "sort('data_produktu')" class="date">Da ...

What is the reason for the 'scrollHeight' being considered 'undefined' in this particular scenario, and why did the iframe encounter an error when switching to the html-file?

This is my first time asking a question, so please forgive any mistakes... I am attempting to create a website using HTML, CSS, and JavaScript on my Raspberry Pi with Apache2. I have written a script for an automatic iframe height function based on the co ...

Should a React application perform a complete refresh when a file is reloaded?

Recently, I delved into the world of React and learned about one of its key benefits: updating only the necessary DOM elements. However, as I began building an app from scratch, I encountered a situation where every time I saved the .js file, it resulted ...

Understanding the concept of event bubbling through the use of querySelector

I am currently working on implementing an event listener that filters out specific clicks within a container. For instance, in the code snippet below I am filtering out clicks on elements with the class UL.head. <div> <ul class="head"> < ...

Fetching requests always seem to remain unfinished

I previously had this code in a different question, but since they are not unrelated, I decided to move it to a new one... Here I am again with the same code, but facing a different issue. My application is set up and running on an express server with a p ...

Using Ajax and PHP to store multiple checkbox selections into the database

I currently have 32 checkboxes on my page that I need to track the checked status for. In my JavaScript, I am looping through each checkbox and assigning a value of '1' for checked and '0' for unchecked. // Example for one checkbox if ...

Can you provide tips on how to center the title on the page?

Currently, I am working on codepen.io and have been tasked with creating a paragraph that includes a title. However, my dilemma lies in the fact that I need this title to be center-aligned without directly altering the "x" value. Unfortunately, CSS is not ...

Is it possible to retain various delimiters after dividing a String?

In the code below, the someString gets split into an array using specified delimiters in separators var separators = ['\\.', '\\(', '\\)', ':', '\\?', '!&apos ...

Adjusting the height of the scrollbar in relation to a div using jScrollPane

I am currently working on a resizable div that utilizes custom scrollbars from jScrollPane. My goal is to position the vertical scrollbar above the resize handle. Is there a way to achieve this? I experimented with adjusting the verticalTrackHeight by al ...

Analyzing viewer engagement by monitoring the duration of video watched using JavaScript

I need a way to monitor video views for individual users, using a table in the database called Viewings. Each viewing is associated with both a user and a video, and keeps track of the duration watched as well as the percentage of the video completed. Whe ...

Troubleshooting overflow problems when centering a UL menu with an unspecified width

Trying to create a demo where the scrollbars are removed when resizing smaller, but adding overflow: hidden causes issues with sub-menus. Demo Link HTML <nav> <ul> <li><a href="#">Menu Item</a></li> ...

What is the best way to ensure that these social icons are perfectly centered on the page across all web browsers?

Visit my website here: foxweb.marist.edu/users/kf79g/contact.php I'm stuck on the final step needed to deploy my website and finish it. The issue I'm facing is with the social icons when viewed on medium and small screens. I want them to be cent ...

What is the best way to align a bootstrap5 card in the center

Would appreciate help centering this card in the web browser. I'm using Bootstrap5 and struggling to get it centered. Can anyone assist me with centering the card using either bootstrap5 or css3? I'm currently utilizing Bootstrap5. The Card < ...

Implementing a feature to insert a horizontal rule button in React Draft Wysiwyg

I am currently working on implementing a custom button in React Draft Wysiwyg that will allow me to add an <hr> tag to my content. Although I have followed the demos and documentation, I have encountered an issue where the custom button successfully ...