avatarIvan Franchin

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

6395

Abstract

class="hljs-keyword">function</span> (<span class="hljs-params"></span>) { <span class="hljs-keyword">const</span> easeljsCanvas = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">"easeljsCanvas"</span>) <span class="hljs-keyword">const</span> box2dCanvas = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">"box2dCanvas"</span>)

    _worldManager = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Box2DCreateJS</span>.<span class="hljs-title class_">WorldManager</span>(
        easeljsCanvas, box2dCanvas, {
            <span class="hljs-attr">world</span>: <span class="hljs-keyword">new</span> box2d.<span class="hljs-title function_">b2World</span>(<span class="hljs-keyword">new</span> box2d.<span class="hljs-title function_">b2Vec2</span>(<span class="hljs-number">0</span>, <span class="hljs-number">10</span>), <span class="hljs-literal">true</span>)
        }
    )
    _worldManager.<span class="hljs-title function_">start</span>()

}

}())</pre></div><h1 id="9358">Create gameLogic function</h1><p id="d327">In <code>myApp.js</code> file, define a function called <code>gameLogic</code> (that will be empty for now) and add the invocation of it inside the <code>initialize</code> function.</p><div id="e6ce"><pre><span class="hljs-variable language_">this</span>.<span class="hljs-property">Box2DCreateJS</span> = <span class="hljs-variable language_">this</span>.<span class="hljs-property">Box2DCreateJS</span> || {};

(<span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) { ...

<span class="hljs-title class_">MyGame</span>.<span class="hljs-property"><span class="hljs-keyword">prototype</span></span>.<span class="hljs-property">initialize</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) {
    ...
    _worldManager.<span class="hljs-title function_">start</span>()

    <span class="hljs-title function_">gameLogic</span>()
}

<span class="hljs-keyword">function</span> <span class="hljs-title function_">gameLogic</span>(<span class="hljs-params"></span>) {
}

}())</pre></div><h1 id="e712">Create the Scenario Limits</h1><p id="efc4">The EaselJS and Box2D canvas have the width of <b>980</b> <b>pixels</b> and the height of <b>500 pixels</b>.</p><figure id="5c95"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*ps_MVOFTpx93-WtKTD2Sgg.png"><figcaption></figcaption></figure><p id="ad03">In order to create the scenario limits, let’s add the following content to <code>gameLogic</code> function. Here, we are using <code>_worldManager</code> to create four <code>static</code> <code>Entity</code> objects: the floor, left and right walls, and the ceiling. All of them are using the same <code>Render</code>, defined in the <code>const</code> variable <code>staticRender</code>.</p><div id="275f"><pre>... <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">gameLogic</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">const</span> <span class="hljs-variable constant_">staticRender</span> = { type: <span class="hljs-string">'draw'</span>, drawOpts: { bgColorStyle: <span class="hljs-string">'solid'</span>, bgSolidColorOpts: { color: <span class="hljs-string">'black'</span> } } }

<span class="hljs-comment">// floor</span>
_worldManager.<span class="hljs-title function_ invoke__">createEntity</span>({
    <span class="hljs-attr">type</span>: <span class="hljs-string">'static'</span>,
    <span class="hljs-attr">x</span>: <span class="hljs-number">490</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">500</span>,
    <span class="hljs-attr">shape</span>: <span class="hljs-string">'box'</span>,
    <span class="hljs-attr">boxOpts</span>: { <span class="hljs-attr">width</span>: <span class="hljs-number">980</span>, <span class="hljs-attr">height</span>: <span class="hljs-number">10</span> },
    <span class="hljs-attr">render</span>: staticRender
})

<span class="hljs-comment">// ceiling</span>
_worldManager.<span class="hljs-title function_ invoke__">createEntity</span>({
    <span class="hljs-attr">type</span>: <span class="hljs-string">'static'</span>,
    <span class="hljs-attr">x</span>: <span class="hljs-number">490</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">0</span>,
    <span class="hljs-attr">shape</span>: <span class="hljs-string">'box'</span>,
    <span class="hljs-attr">boxOpts</span>: { <span class="hljs-attr">width</span>: <span class="hljs-number">980</span>, <span class="hljs-attr">height</span>: <span class="hljs-number">10</span> },
    <span class="hljs-attr">render</span>: staticRender
})

<span class="hljs-comment">// left wall</span>
_worldManager.<span class="hljs-title function_ invoke__">createEntity</span>({
    <span class="hljs-attr">type</span>: <span class="hljs-string">'static'</span>,
    <span class="hljs-attr">x</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">250</span>,
    <span class="hljs-attr">shape</span>: <span class="hljs-string">'box'</span>,
    <span class="hljs-attr">boxOpts</span>: { <span class="hljs-attr">width</span>: <span class="hljs-number">10</span>, <span class="hljs-attr">height</span>: <span class="hljs-number">500</span> },
    <span class="hljs-attr">render</span>: staticRender
})

<span class="hljs-comment">// right wall</span>
_worldManager.<span class="hljs-title function_ invoke__">createEntity</span>({
    <span class="hljs-attr">type</span>: <span class="hljs-string">'static'</span>,
    <span class="hljs-attr">x</span>: <span class="hljs-number">980</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">250</span>,
    <span class="hljs-attr">shape</span>: <span class="hljs-string">'box'</span>,
    <span class="hljs-attr">boxOpts</span>: { <span class="hljs-attr">width</span>: <span class="hljs-number">10</span>, <span class="hljs-attr">height</s

Options

pan>: <span class="hljs-number">500</span> }, <span class="hljs-attr">render</span>: staticRender }) } ...</pre></div><p id="7e60">In the picture below, it’s shown how the <code>static</code> Entities are placed in the canvas.</p><figure id="1955"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*09RDPiAV7BENvSzH7l6jOQ.png"><figcaption></figcaption></figure><p id="5ccb">Let’s check how it’s getting so far.</p><figure id="1daf"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*79Vo1l5yft8yFJZ0rAQUog.png"><figcaption></figcaption></figure><h1 id="a29e">Create the Ball</h1><p id="08a2">Let’s now create a ball that falls from the top-center of the screen. For it, add the following code at the end of the <code>gameLogic</code> function. It uses the <code>_worldManager</code> to create a <code>dynamic</code> <code>Entity</code> that represent the ball.</p><div id="b0b2"><pre>... <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">gameLogic</span>(<span class="hljs-params"></span>) </span>{ ...

<span class="hljs-comment">// ball</span>
_worldManager.<span class="hljs-title function_ invoke__">createEntity</span>({
    <span class="hljs-attr">type</span>: <span class="hljs-string">'dynamic'</span>,
    <span class="hljs-attr">x</span>: <span class="hljs-number">490</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">250</span>,
    <span class="hljs-attr">shape</span>: <span class="hljs-string">'circle'</span>,
    <span class="hljs-attr">circleOpts</span>: { <span class="hljs-attr">radius</span>: <span class="hljs-number">40</span> },
    <span class="hljs-attr">render</span>: {
        <span class="hljs-attr">type</span>: <span class="hljs-string">'draw'</span>,
        <span class="hljs-attr">drawOpts</span>: {
            <span class="hljs-attr">bgColorStyle</span>: <span class="hljs-string">'solid'</span>,
            <span class="hljs-attr">bgSolidColorOpts</span>: { <span class="hljs-attr">color</span>: <span class="hljs-string">'white'</span> },
            <span class="hljs-attr">borderWidth</span>: <span class="hljs-number">5</span>
        },
    },
    <span class="hljs-attr">fixtureDefOpts</span>: { <span class="hljs-attr">restitution</span>: <span class="hljs-number">0.5</span> }
})

} ...</pre></div><p id="416b">In the following image, it’s displayed where the ball is placed. This center is exactly the middle of the canvas (x: 490, y: 250). Besides, it has the radius of <b>40 pixels</b>.</p><figure id="3645"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*x9ZLl1nEKMjKWvm938qY-w.png"><figcaption></figcaption></figure><p id="fc5b">By checking how it’s so far, you should see something like</p><figure id="a71e"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*8tUju-xW5xN92betahXwOA.png"><figcaption></figcaption></figure><h1 id="0fe3">Enable Cursor to Play with the Ball</h1><p id="bad5">Let’s enable the cursor so that we can get the ball, drag it around or throw it. For it, we need to include the <code>TouchMouseHandler.js</code><b> </b>in <code>index.html</code></p><div id="4746"><pre><span class="hljs-meta"><!DOCTYPE <span class="hljs-keyword">html</span>></span> <span class="hljs-tag"><<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>></span> <span class="hljs-tag"><<span class="hljs-name">head</span>></span> ... <span class="hljs-tag"><<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"box2dcreatejs/js/Box2DCreateJS/TouchMouseHandler.js"</span>></span><span class="hljs-tag"></<span class="hljs-name">script</span>></span> ... <span class="hljs-tag"></<span class="hljs-name">head</span>></span> ... <span class="hljs-tag"></<span class="hljs-name">html</span>></span></pre></div><p id="7af0">Then, in <code>myApp.js</code>, we need to add the following line. It uses the <code>_worldManager</code> variable to call the <code>createTouchMouseHandler</code> function</p><div id="dc52"><pre>... MyApp<span class="hljs-selector-class">.prototype</span><span class="hljs-selector-class">.initialize</span> = function () { ... _worldManager<span class="hljs-selector-class">.start</span>() _worldManager<span class="hljs-selector-class">.createTouchMouseHandler</span>()

<span class="hljs-built_in">gameLogic</span>()

} ...</pre></div><p id="4387">Let’s check…</p><p id="cd18">Nice! Now we can play with the ball and throw it around!</p><figure id="68f3"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*08W1vlsLaWVMcTU-wH5cDA.gif"><figcaption></figcaption></figure><h1 id="bd91">Additional Readings</h1><p id="fdf6">The source code can be found at <a href="https://github.com/ivangfr/box2dcreatejs"><b>Box2DCreateJS</b> <b>GitHub</b> <b>Repository</b></a>.</p><div id="4223" class="link-block"> <a href="https://readmedium.com/box2dcreatejs-creating-a-monster-truck-game-225193431735"> <div> <div> <h2>Box2DCreateJS: Creating a monster truck game</h2> <div><h3>Building an exciting monster truck game from scratch</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*tSKOY21nQ77k4vZM)"></div> </div> </div> </a> </div><h1 id="6525">Support and Engagement</h1><p id="c13e">If you enjoyed this article and would like to show your support, please consider taking the following actions:</p><ul><li>👏 Engage by clapping, highlighting, and replying to my story. I’ll be happy to answer any of your questions;</li><li>🌐 Share my story on Social Media;</li><li>🔔 Follow me on: <a href="https://medium.com/@ivangfr">Medium</a> | <a href="https://www.linkedin.com/in/ivanfranchin/">LinkedIn</a> | <a href="https://twitter.com/ivangfr">Twitter</a> | <a href="https://github.com/ivangfr">GitHub</a>;</li><li>✉️ <a href="https://medium.com/@ivangfr/subscribe">Subscribe to my newsletter</a>, so you don’t miss out on my latest posts.</li></ul></article></body>

Box2DCreateJS = Box2d + CreateJS

Box2DCreateJS: Creating a ball and interacting with it using the cursor

Interactive ball creation and cursor interaction tutorial

Photo by Glen Carrie on Unsplash

In this article, I will show you how to create a simple 2D physics scenario using Box2DCreateJS.

If you don’t know what Box2DCreateJS is, take a look at the article linked below:

Our scenario has gravity and is surrounded by a floor, left and right walls, and a ceiling. Besides, inside it, we will add a white ball we can interact with using the cursor.

By the end of the article, this is what we will achieve!

Before start coding, let’s create the project initial setup as explained in the article linked below:

Once we have our project ready, let’s get started!

Import Box2DCreateJS

Let’s include Box2DCreateJS library into index.html. For it, include the following lines

<!DOCTYPE html>
<html lang="en">
  
    <head>
        ...
        <script src="box2dcreatejs/js/Box2dWeb/Box2dWeb-2.1.a.3.js"></script>
        <script src="box2dcreatejs/js/CreateJS/easeljs-1.0.0.min.js"></script>
    
        <script src="box2dcreatejs/js/Box2DCreateJS/WorldManager.js"></script>
        <script src="box2dcreatejs/js/Box2DCreateJS/Render.js"></script>
        <script src="box2dcreatejs/js/Box2DCreateJS/Entity.js"></script>

        <script src="MyApp.js"></script>
        ...
    </head>
    ...
</html>

Create and Start the WorldManager

In myApp.js file, define a _worldManager variable and instantiate it inside the initialize function. Then, still inside the initialize function, let’s start the _worldManager by calling the start function.

this.Box2DCreateJS = this.Box2DCreateJS || {};

(function () {

    function MyGame() {
        this.initialize()
    }

    Box2DCreateJS.MyGame = MyGame

    let _worldManager

    MyGame.prototype.initialize = function () {
        const easeljsCanvas = document.getElementById("easeljsCanvas")
        const box2dCanvas = document.getElementById("box2dCanvas")

        _worldManager = new Box2DCreateJS.WorldManager(
            easeljsCanvas, box2dCanvas, {
                world: new box2d.b2World(new box2d.b2Vec2(0, 10), true)
            }
        )
        _worldManager.start()
  }

}())

Create gameLogic function

In myApp.js file, define a function called gameLogic (that will be empty for now) and add the invocation of it inside the initialize function.

this.Box2DCreateJS = this.Box2DCreateJS || {};

(function () {
    ...

    MyGame.prototype.initialize = function () {
        ...
        _worldManager.start()

        gameLogic()
    }

    function gameLogic() {
    }

}())

Create the Scenario Limits

The EaselJS and Box2D canvas have the width of 980 pixels and the height of 500 pixels.

In order to create the scenario limits, let’s add the following content to gameLogic function. Here, we are using _worldManager to create four static Entity objects: the floor, left and right walls, and the ceiling. All of them are using the same Render, defined in the const variable staticRender.

...
function gameLogic() {
    const staticRender = {
        type: 'draw',
        drawOpts: {
            bgColorStyle: 'solid',
            bgSolidColorOpts: { color: 'black' }
        }
    }

    // floor
    _worldManager.createEntity({
        type: 'static',
        x: 490, y: 500,
        shape: 'box',
        boxOpts: { width: 980, height: 10 },
        render: staticRender
    })

    // ceiling
    _worldManager.createEntity({
        type: 'static',
        x: 490, y: 0,
        shape: 'box',
        boxOpts: { width: 980, height: 10 },
        render: staticRender
    })

    // left wall
    _worldManager.createEntity({
        type: 'static',
        x: 0, y: 250,
        shape: 'box',
        boxOpts: { width: 10, height: 500 },
        render: staticRender
    })

    // right wall
    _worldManager.createEntity({
        type: 'static',
        x: 980, y: 250,
        shape: 'box',
        boxOpts: { width: 10, height: 500 },
        render: staticRender
    })
}
...

In the picture below, it’s shown how the static Entities are placed in the canvas.

Let’s check how it’s getting so far.

Create the Ball

Let’s now create a ball that falls from the top-center of the screen. For it, add the following code at the end of the gameLogic function. It uses the _worldManager to create a dynamic Entity that represent the ball.

...
function gameLogic() {
    ...

    // ball
    _worldManager.createEntity({
        type: 'dynamic',
        x: 490, y: 250,
        shape: 'circle',
        circleOpts: { radius: 40 },
        render: {
            type: 'draw',
            drawOpts: {
                bgColorStyle: 'solid',
                bgSolidColorOpts: { color: 'white' },
                borderWidth: 5
            },
        },
        fixtureDefOpts: { restitution: 0.5 }
    })
}
...

In the following image, it’s displayed where the ball is placed. This center is exactly the middle of the canvas (x: 490, y: 250). Besides, it has the radius of 40 pixels.

By checking how it’s so far, you should see something like

Enable Cursor to Play with the Ball

Let’s enable the cursor so that we can get the ball, drag it around or throw it. For it, we need to include the TouchMouseHandler.js in index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        ...
        <script src="box2dcreatejs/js/Box2DCreateJS/TouchMouseHandler.js"></script>
        ...
    </head>
    ...
</html>

Then, in myApp.js, we need to add the following line. It uses the _worldManager variable to call the createTouchMouseHandler function

...
MyApp.prototype.initialize = function () {
    ...
    _worldManager.start()
    _worldManager.createTouchMouseHandler()

    gameLogic()
}
...

Let’s check…

Nice! Now we can play with the ball and throw it around!

Additional Readings

The source code can be found at Box2DCreateJS GitHub Repository.

Support and Engagement

If you enjoyed this article and would like to show your support, please consider taking the following actions:

  • 👏 Engage by clapping, highlighting, and replying to my story. I’ll be happy to answer any of your questions;
  • 🌐 Share my story on Social Media;
  • 🔔 Follow me on: Medium | LinkedIn | Twitter | GitHub;
  • ✉️ Subscribe to my newsletter, so you don’t miss out on my latest posts.
Game Development
Box2d
Createjs
JavaScript
Technology
Recommended from ReadMedium