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

**URL:** <https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724>\
**Category:** web dev\
**Created:** [February 4, 2023, 12:11am UTC](https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724 "2023-02-04T00:11:10Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![AmiiboAmigos](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/amiiboamigos/32/19755_2.png) [@AmiiboAmigos](https://forum.kirupa.com/u/AmiiboAmigos)\
**Post date:** [February 4, 2023, 12:11am UTC](https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724/1 "2023-02-04T00:11:10Z")

</div>

Starting my next project and already can’t figure out how to translate this: [Join AnaeliRivera's "EnemyTest" - Replit](https://replit.com/join/micyigfjll-anaelirivera) and add into [Join AnaeliRivera's "Game" - Replit](https://replit.com/join/tytzbzpugq-anaelirivera).  
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.

---

<div class="post-metadata">

**Author:** ![PAEz](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/paez/32/19607_2.png) [@PAEz](https://forum.kirupa.com/u/PAEz)\
**Post date:** [February 4, 2023, 11:19am UTC](https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724/2 "2023-02-04T11:19:28Z")

</div>

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](https://replit.com/@PeterIrlam/Game#index.html)

---

<div class="post-metadata">

**Author:** ![AmiiboAmigos](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/amiiboamigos/32/19755_2.png) [@AmiiboAmigos](https://forum.kirupa.com/u/AmiiboAmigos)\
**Post date:** [February 5, 2023, 11:23pm UTC](https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724/3 "2023-02-05T23:23:23Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![PAEz](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/paez/32/19607_2.png) [@PAEz](https://forum.kirupa.com/u/PAEz)\
**Post date:** [February 8, 2023, 6:44am UTC](https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724/4 "2023-02-08T06:44:16Z")

</div>

Sorry, you wanted to see both combined? OK… [EnemyTest + Player - Class's - Replit](https://replit.com/@PeterIrlam/EnemyTest-Player-Classs#index.html)  
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.

---

<div class="post-metadata">

**Author:** ![AmiiboAmigos](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/amiiboamigos/32/19755_2.png) [@AmiiboAmigos](https://forum.kirupa.com/u/AmiiboAmigos)\
**Post date:** [February 9, 2023, 12:35am UTC](https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724/5 "2023-02-09T00:35:45Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [February 9, 2023, 4:40am UTC](https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724/6 "2023-02-09T04:40:20Z")

</div>

This article can help!

> **[Using Classes in JavaScript](https://www.kirupa.com/javascript/classy_way_to_create_objects.htm)**
>
> Think properly creating objects in JavaScript is difficult? Use classes to simplify that for you!

---

<div class="post-metadata">

**Author:** ![PAEz](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/paez/32/19607_2.png) [@PAEz](https://forum.kirupa.com/u/PAEz)\
**Post date:** [February 9, 2023, 7:34am UTC](https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724/7 "2023-02-09T07:34:42Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![AmiiboAmigos](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/amiiboamigos/32/19755_2.png) [@AmiiboAmigos](https://forum.kirupa.com/u/AmiiboAmigos)\
**Post date:** [February 18, 2023, 10:12pm UTC](https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724/8 "2023-02-18T22:12:22Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![PAEz](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/paez/32/19607_2.png) [@PAEz](https://forum.kirupa.com/u/PAEz)\
**Post date:** [February 22, 2023, 1:06pm UTC](https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724/10 "2023-02-22T13:06:51Z")

</div>

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 😜 , 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.

> **[Phaser - A fast, fun and free open source HTML5 game framework](https://phaser.io/)**
>
> Desktop and Mobile HTML5 game framework. A fast, free and fun open source framework for Canvas and WebGL powered browser games.

---

<div class="post-metadata">

**Author:** ![AmiiboAmigos](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/amiiboamigos/32/19755_2.png) [@AmiiboAmigos](https://forum.kirupa.com/u/AmiiboAmigos)\
**Post date:** [February 25, 2023, 3:08am UTC](https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724/11 "2023-02-25T03:08:57Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![AmiiboAmigos](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/amiiboamigos/32/19755_2.png) [@AmiiboAmigos](https://forum.kirupa.com/u/AmiiboAmigos)\
**Post date:** [March 18, 2023, 2:45am UTC](https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724/12 "2023-03-18T02:45:39Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![divine\_eye](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/divine_eye/32/23294_2.png) [@divine\_eye](https://forum.kirupa.com/u/divine_eye)\
**Post date:** [August 29, 2023, 4:41pm UTC](https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724/14 "2023-08-29T16:41:21Z")

</div>

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

```auto
<!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

```auto
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

```auto
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.

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [August 29, 2023, 6:23pm UTC](https://forum.kirupa.com/t/need-help-coding-enemies-to-new-web-game-in-html-javascript/656724/15 "2023-08-29T18:23:48Z")

</div>

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