Feature Focus: JavaScript Coding

13
Official Construct Post
Ashley's avatar
Ashley
  • 16 Sep, 2022
  • 1,645 words
  • ~7-11 mins
  • 2,801 visits
  • 10 favourites

Construct's visual block system can produce amazing results without having to write a single line of code. However if you want to go even further - or you're interested in learning some real-world programming skills - then you can also write JavaScript code in Construct.

Feature Focus is a series of blog posts and videos where we occasionally highlight some of the best features of Construct. JavaScript is a mature and fully-featured programming language used widely across the software industry. There's far too much to it to cover in one blog post! We'll just highlight how it's used in Construct and some of the cool things you can do with it.

Our past Feature Focuses have covered:

Getting started with JavaScript

JavaScript can do incredible things with outstanding performance, but it's also relatively easy to learn.

If you're a complete beginner, try our Get started with JavaScript interactive tour for a step-by-step introduction. Then try our own 13-part tutorial series Learn JavaScript in Construct. We've had great feedback on that so if you've been waiting for an easy way to learn, give it a go!

If you already know some JavaScript, our Construct for JavaScript developers quick-start guide summarises what you need to know in brief.

Dip your toe in the water

Construct lets you seamlessly transition from its visual block system to a professional programming language. You can add snippets of JavaScript code in the place of an action, as shown below.

Some JavaScript code in an event block.Some JavaScript code in an event block.

Move on up

You can mix and match blocks and JavaScript code, including with some unique features to integrate blocks and code, as shown in the Integrating events with script example.

Then you can go all the way to writing entire projects in pure JavaScript code, as shown in the Ghost Shooter Code example.

A script file from Ghost Shooter Code.A script file from Ghost Shooter Code.

There's always still the visual blocks if you want them though. Coding things like menu systems or user interfaces can involve a lot of tricky and unexciting code. Using event sheets for those parts can help you skip the boring parts and get things done quickly and easily! And don't forget you can design UIs with HTML and CSS to use powerful, well-known features to get quick results.

Language features

JavaScript has too many features to list here, and it's always getting more too. You can find some of the more developed upcoming feature proposals from the imaginatively named Technical Committee 39 (TC39) who manage the JavaScript language specification.

In the mean time here are just a few of the things we think are cool about JavaScript!

JavaScript Modules let you organise your code in a clean and re-usable way, with import and export statements.

import Utils from "./utils.js";

Async functions let you write code that handles asynchronous calls almost as straightforwardly as standard synchronous code.

async function loadData()
{
	const response = await fetch("mydata.json");
	const json = await response.json();
	console.log("Loaded data: ", json);
}

Arrow functions are a succinct way to write functions, useful for things like callbacks. They can be async too!

runOnStartup(async runtime =>
{
	// Load things for the game!
});

There's a comprehensive syntax for classes, including newer additions like public fields (accessible anywhere) and private fields (only accessible to the class).

class MyClass {
	publicField = "hello";		// a public field
	#privateField = "world";	// a private field
	
	constructor()
	{
		console.log(this.publicField + this.#privateField);
	}
}

There's even Web Workers which let you load another script in a separate JavaScript context that runs in parallel, providing a way to use multithreaded code in JavaScript. Messages can be passed to and from the worker, which is a safe way to communicate without the risk of nightmare concurrency bugs that afflict unsafe languages.

const worker = new Worker("workerscript.js");
worker.onmessage = (e => console.log("Received message: ", e.data));
worker.postMessage("start-task");

As an industry-standard language, you can also use tools like Node.js and Deno to write things like servers and tools using the same programming language. There's no need to learn two languages and have to switch between them to get something like a custom server running. JavaScript is thoroughly tested to work exactly the same across a wide range of platforms, and it has a strong focus on backwards compatibility, avoiding ever making breaking changes. And as it remains one of the most popular programming languages in the world, you could even get a job writing JavaScript.

There's a great deal more we could go in to, but we'll move on anyway. Want to learn more? Dig in to the JavaScript Reference on the MDN web docs.

Construct APIs

There's the standard JavaScript language which works consistently across all the browsers and tools that use it across the industry. Then there's the things specific to Construct, like the way you get a Sprite instance and set its position. These are the APIs (Application Programming Interfaces) specific to Construct. We have a broad set of APIs allowing your code to take advantage of everything Construct can do, from effects to behaviors (and in the latest beta, even multiplayer networking).

Some tools design their own custom programming languages, with a fraction of the features and performance of professional programming languages like JavaScript. (We've blogged before about why we believe this is a mistake.) Sometimes one of the reasons cited is so they can integrate it with their tool. But we have integrated JavaScript with Construct too - you don't have to have a custom language for that! An example of that is if you have a sprite named MySprite in your project, you can access it with runtime.objects.MySprite. You can then get and position an instance like this.

// Get the first instance of MySprite
const inst = runtime.objects.MySprite.getFirstInstance();

// Set its position to (100, 200)
inst.x = 100;
inst.y = 200;

Construct provides autocomplete while writing code, even including suggesting the names of the objects in your project.

Autocompleting object names from the project while writing JavaScript code.Autocompleting object names from the project while writing JavaScript code.

Construct also integrates nicely with JavaScript language features, using things like generator functions to work with JavaScript's for...of loops.

// Set all instances size to 100x100
for (const inst of runtime.objects.MySprite.instances())
{
	inst.width = 100;
	inst.height = 100;
}

You can use the same addEventListener-style API as browsers use to listen for Construct-specific events, like an instance being destroyed. This example also nicely demonstrates arrow functions and template literals working together to produce elegant code.

runtime.objects.MySprite.addEventListener("instancedestroy", e =>
{
	console.log(`Instance UID '${e.instance.uid}' destroyed`);
});

Each kind of plugin and behavior has its own script interface to provide APIs specific to that plugin or behavior. These can all be found in the scripting reference in the Scripting section of the manual. For example the Sprite interface provides a setAnimation() method to change the current animation; the Text interface provides a text property; and the 3D Camera interface provides a lookAtPosition() method to set a 3D view (see our past blog on Construct's 3D features). You can even customise the built-in classes further by subclassing instances, such as to make Player and Enemy sprites use different customised classes, even though they are both Sprites.

Behavior APIs

Construct's behaviors let you get instant results, such as being able to quickly make a platform movement. You can use JavaScript code to access these behaviors too, taking advantage of Construct's various built-in features. For example the Tween behavior provides a comprehensive API for using tweens, which can be accessed like this.

const inst = runtime.objects.MySprite.getFirstInstance();
const Tween = inst.behaviors.Tween;
Tween.startTween("size", [200, 200], 1, "out-sine");

The Pathfinding behavior uses the A* algorithm and distributes pathfinding calculations across multiple web workers, allowing use of multiple CPU cores to perform pathfinding, providing both incredible performance and avoiding heavy calculations affecting the framerate. This too can all be accessed from code using the Pathfinding behavior interface, as shown below - also demonstrating use use of await in an asynchronous function, and destructuring.

const inst = runtime.objects.MySprite.getFirstInstance();
const Pathfinding = inst.behaviors.Pathfinding;

// Find a path to (600, 400), and wait for the calculation to finish.
const foundPath = await Pathfinding.findPath(600, 400);

if (foundPath)
{
	// Log all path nodes to the console
	for (let i = 0, len = Pathfinding.getNodeCount(); i < len; ++i)
	{
		const [nodeX, nodeY] = Pathfinding.getNodeAt(i);
		console.log(`Path node ${i}: (${nodeX}, ${nodeY})`);
	}
}

Developer tools

Browsers have sophisticated developer tools, including console logging, a fully-featured debugger, listing all network requests, memory usage analysis, and a detailed performance profiler too, all of which comes free with every browser. Our documentation includes a primer on using dev tools, and browser makers provide lots more of their own documentation.

The performance profiler from Chrome Dev Tools.The performance profiler from Chrome Dev Tools.

Learn more

If you want to get in to using JavaScript in Construct, we recommend our 13-part tutorial series Learn JavaScript in Construct. If you already know some JavaScript check out our Construct for JavaScript developers quick start guide. For a full reference on using JavaScript in Construct, see the scripting section of the manual.

Conclusion

JavaScript is an amazing programming language, having had decades of development on the language and an ecosystem of tools around it. It's also incredibly fast, with performance that can even far exceed other languages compiled to C++, and in some cases it can come close to the performance of C++ itself. We've closely integrated JavaScript with Construct so you can take advantage of everything Construct provides, from Sprites to multithreaded pathfinding calculations, while learning real-world skills that will help you in your next steps in the world of programming. There's never been a better time to get started with JavaScript in Construct.

Subscribe

Get emailed when there are new posts!

  • 4 Comments

  • Order by
Want to leave a comment? Login or Register an account!
  • THANK U !! I LOVE JAVASCRIPT

  • javascript kinda sucks... but cool blog bro

    edit: nvm javascript is cool for construct i was wrong

  • Im doing almost all game logic in TypeScript (30k+ lines of code already). And using Construct 3 because i really like the editor and workflow in general! Even though some parts of the engine is still pretty limited, im glad i can work that way and really happy to see Construct 3 getting updated, so really looking into future of c3!

  • Construct has been awesome for my little games, I use javascript to make my games work with existing web technology. For example this simple wheel game pulls its data from a real crypto blockchain contract, showing burnt tokens, pot size, and last few winners. Though this game takes in a "token" and pays out in a crypto coin, you could tie construct to any kind of API or other web technology super easily!

    wos.notallmine.net