Blocks_ipynb_2_
Hack: Falling Block with Gravity
Task: Create a moving block that falls from the top of the screen and simulates gravity. The block should start from a random position at the top of the canvas, and gravity should pull it down to the bottom of the canvas. Your task is to:
- Implement the movement so that the block falls under the effect of gravity.
- Ensure the block stops at the bottom of the screen when it reaches the ground.
Instructions:
- Create the Block: The block should be represented as an object with properties such as
x
,y
,width
,height
, andcolor
. - Apply Gravity: The block should accelerate downward due to gravity. This can be achieved by updating the block’s vertical speed (
speedY
) each frame. - Stop at the Bottom: When the block hits the bottom of the screen, it should stop falling and remain there.
- Randomize Horizontal Position: The block’s horizontal position (
x
) should be randomized when the game starts.
- Create the Block: The block should be represented as an object with properties such as
- Below is an example of how its implemented, but DONT COPY AND PASTE IT, implement it into the level of your choice and play around with the values. We wont accept just duplicates since this code isnt fully correct.
import Npc from './Npc.js';
class FallingBlock extends Npc {
constructor(data = null, gameEnv = null) {
super(data, gameEnv);
this.fallSpeed = data?.fallSpeed || 2;
this.maxY = data?.maxY || gameEnv.innerHeight;
this.height = this.spriteData.pixels.height * this.spriteData.SCALE_FACTOR;
}
update() {
if (this.position.y + this.height < this.maxY) {
this.position.y += this.fallSpeed;
} else {
this.position.y = this.maxY - this.height;
}
this.draw();
}
}
export default FallingBlock;