Need help coding enemies to new web game in HTML/JavaScript

Starting my next project and already can’t figure out how to translate this: Join AnaeliRivera's "EnemyTest" - Replit and add into Join AnaeliRivera's "Game" - Replit.
Whenever I do so, the whole game canvas disappears. I’m looking to add “enemies” that follow the player gamePiece, can anyone give me some insight on this? much appreciated.

Seems it was setting the background-color for canvas was making the canvas not visible. So getting rid of that and making the clear fillRect instead fixes that. Game - Replit

1 Like

thanks, wasn’t sure how to fix that either. it wasnt a problem in dreamweaver.

Sorry, you wanted to see both combined? OK… EnemyTest + Player - Class's - Replit
I couldnt resist and I also converted it to use Class’s and made a few other little tweaks. You should look into Class’s as you where using two different ways to handle that sorta stuff in your code and class’s are just better.
If you have any questions as to why I did anything just ask.

Wow, Thank you!
I did look more into Class’s in JavaScript, gained an even better understanding too.
although I’m wondering what paint(ctx) is about.

and I assume the class Entity refers to both player and follower, right?

I’m still pretty new to JavaScript and I yearn for a deeper understanding. lol

This article can help!

What paint(ctx) is about… I have two rules that I always try to follow when doing components “Separation of concerns” and “code inside the component should have no understanding of whats outside of it”. The separation one is about making each component do one specific thing. Can be hard trying to decide how much to split stuff up and what belongs where some times. And the other one is about the code inside the function only knows about what it was told about, it never just knows about other components/code outside of itself unless that info was passed to it. This makes sure your code is more reusable amongst other things. For instance in your code you have let ctx = myGameArea.context; inside component. So now to use component you have to have the object named myGameArea, it cant be named anything else. It also just helps me visualize how things are connected easier. So with the entities I wasnt sure if to pass the gameArea during construction or the way I did it. The way I did it is easier for switching context which I used a while back so guess it was still in my head.|

Entity is the base component that both player and follower extend from. In your code Enemy extends from GamePiece so thought Id show you the class version. Youd be best to read about class’s somewhere (MDN as usual) to understand all that.

I see,
Then how should I program collision between player and follower? and were should I put said code?

I think you should be reading a lot of articles on game creation and looking at using a library.
There are a bunch of ways of doing collision detection…AABB (non rotating rectangles), SAT (convex polygons), circle, pixel perfect (pixel to pixel or bit masks), etc. For this youd prolly want SAT and I aint writing that :stuck_out_tongue_winking_eye: , so Id use a library. And your going to keep on having questions as theres still a lot more to all this.
If I was you Id start looking for a library. As I havent looked at this sorta stuff for years the only thing that comes to mind is Phaser. Its not as active as it once was but is still being updated and all that. I like that one because there are LOTS of tutorials and their forums still have some activity. It has everything and the kitchen sink. I havent written a game in literal decades but I want to sooner or later and Id prolly just use Phaser because I like a lot of the ways it does things. Failing that itd prolly be PixiJS with a SAT library, no idea for audio.
I could add collision detection to your example but prolly not till the weekend as Im going through a no energy phase…again…sorry.

no problem!
I’m doing some research and figuring things out bit by bit.
your help was and still is incredibly helpful. thank you so much!

So, I made a few changes.
However, the WebView just disappears. this was an attempt to add collision/. If there is a collision, game is supposed to stop by calling the stop()method.
I’m not sure if I did this all right.
this code has gone through many changes. I was attempting to add circular objects that explode into smaller circles that act as projectiles to the enemy. but that was too much so I thought I could focus on collision detection.

Keep in mind that this is a simplified example, and you can expand upon it to add more complexity and features as needed.

1. HTML Structure:

First, let’s set up the HTML structure of your game. Create an HTML file (e.g., index.html) and add the necessary elements:

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Your Web Game</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <canvas id="gameCanvas"></canvas>
    <script src="game.js"></script>
</body>
</html>

2. CSS Styling (styles.css):

You can create a CSS file to style your game canvas and other elements as needed:

css

body {
    margin: 0;
    overflow: hidden;
}

canvas {
    display: block;
}

3. JavaScript Game Logic (game.js):

Now, let’s work on the JavaScript code for your game. This example will demonstrate how to create a simple enemy class and spawn enemies on the canvas.

javascript

const canvas = document.getElementById("gameCanvas");
const ctx = canvas.getContext("2d");

// Set canvas dimensions
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// Enemy class
class Enemy {
    constructor(x, y, speed) {
        this.x = x;
        this.y = y;
        this.speed = speed;
    }

    update() {
        this.x -= this.speed;
    }

    draw() {
        ctx.fillStyle = "red";
        ctx.fillRect(this.x, this.y, 30, 30); // Change dimensions as needed
    }
}

// Create an array to hold enemies
const enemies = [];

// Game loop
function gameLoop() {
    requestAnimationFrame(gameLoop);
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Create a new enemy at regular intervals
    if (Math.random() < 0.02) {
        const enemyY = Math.random() * canvas.height;
        const enemySpeed = Math.random() * 5 + 1;
        enemies.push(new Enemy(canvas.width, enemyY, enemySpeed));
    }

    // Update and draw enemies
    for (const enemy of enemies) {
        enemy.update();
        enemy.draw();
    }
}

// Start the game loop
gameLoop();

In this example, we’ve created a basic game loop that spawns enemies on the canvas at regular intervals. Each enemy is an instance of the Enemy class, which has properties like x, y, and speed. The update method moves the enemies across the screen, and the draw method renders them on the canvas.

Remember that this is just a starting point, and you can enhance and customize the enemy behavior, graphics, and interactions based on your game’s design and mechanics. Additionally, you might want to consider using game libraries or frameworks to simplify development, especially as your game becomes more complex.

1 Like

That is a really nice example, @divine_eye. Welcome to the forums :slight_smile:

1 Like