Learn JavaScript in Construct, part 11: Construct APIs

14

Index

Features on these Courses

Attached Files

The following files have been attached to this tutorial:

.c3p

move-sprite.c3p

Download now 62.55 KB
.c3p

using-script-file.c3p

Download now 62.64 KB
.c3p

keyboard-controls-template.c3p

Download now 62.62 KB
.c3p

modify-sprites-template.c3p

Download now 62.92 KB

Stats

9,312 visits, 22,964 views

Tools

Translations

This tutorial hasn't been translated.

License

This tutorial is licensed under CC BY-NC 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Published on 3 Dec, 2021. Last updated 16 Dec, 2021

Some more examples

Let's briefly cover some more things you can do with Construct's APIs. Download the project below and open it in Construct. This provides a template for modifying sprites with JavaScript code - there are 12 sprites, the Mouse object is included, and main.js is pre-filled with code to handle a click anywhere on the page, but it does not yet do anything when a click happens.

.C3P

modify-sprites-template.c3p

Download now 62.92 KB

Note this project uses the "click" event of document to detect a click anywhere on the page.

Let's try entering some different code in the OnClick function.

Set random angles

The IObjectClass method instances() can be used to iterate all the instances of the object type. In short, this means you can use it with a 'for-of' loop to repeat once per instance.

Setting every instance's angleDegrees to a random number from 0-360 will point every instance in a random direction. Try the following code for OnClick:

function OnClick(runtime)
{
	for (let inst of runtime.objects.Sprite.instances())
	{
		inst.angleDegrees = Math.random() * 360;
	}
}

Preview the project. Now every time you click, all the pigs change to a random angle!

It's worth noting that the spread ... operator can also be used to get an array of everything that would be iterated by 'for-of'. The below example shows getting an array of all 12 Sprite instances and logging it to the console. It then also changes just the last sprite to a random angle, demonstrating accessing the array.

function OnClick(runtime)
{
	let arr = [...runtime.objects.Sprite.instances()];
	console.log("Array of all instances: ", arr);
	
	// Set last sprite to random angle
	arr.at(-1).angleDegrees = Math.random() * 360;
}

Line up sprites

The following code increments a position by 30 for every instance, setting their X and Y co-ordinates to the current value, which lines them up in a diagonal line.

function OnClick(runtime)
{
	let pos = 30;
	
	for (let inst of runtime.objects.Sprite.instances())
	{
		inst.x = pos;
		inst.y = pos;
		
		pos += 30;
	}
}

Random offset

The following code offsets every sprite instance's position by a random number from -10 to 10, causing them to jiggle around if you click repeatedly.

function OnClick(runtime)
{
	for (let inst of runtime.objects.Sprite.instances())
	{
		inst.x += Math.random() * 20 - 10;
		inst.y += Math.random() * 20 - 10;
	}
}

Move random instance to mouse

The following code will pick a random instance on a click and move it to the mouse position.

function OnClick(runtime)
{
	// Get array of all Sprite instances
	let arr = [...runtime.objects.Sprite.instances()];
	
	// Pick a random instance
	let inst = arr[Math.floor(Math.random() * arr.length)];
	
	// Move that instance to the mouse position (on layer 0)
	inst.x = runtime.mouse.getMouseX(0);
	inst.y = runtime.mouse.getMouseY(0);
	
	// Also move it to the top of Z order
	inst.moveToTop();
}

Note that in this example:

  • The spread ... operator is used to get an array of all instances
  • Math.random() * arr.length gets a random number up to the length of an array, but this includes fractions. We want a whole number so we use Math.floor(Math.random() * arr.length) to get a random array index and pick a random instance.
  • Similar to using the keyboard, runtime.mouse accesses the Mouse script interface providing the Mouse object is added to the project. This provides getMouseX and getMouseY methods to get the mouse position on a layer. In this case the layer is given as an index, so 0 is passed for the first (and only) layer.

Try coming up with your own ways to change the sprites instances!

Conclusion

In this part we've covered:

  • Using the built-in runtime variable in scripts in event sheets
  • Accessing object types and instances via runtime.objects
  • Referring to Construct's references for the available APIs in the documentation
  • Using runOnStartup in a script file to get access to runtime
  • Handling runtime events with addEventListener, including the "beforeprojectstart" and "tick" events
  • Handling instance events like button clicks
  • Using keyboard input to control a sprite
  • Various examples of how to modify multiple sprites with JavaScript code

Learn more

If you want to dig deeper, you can learn more about Construct's APIs in the scripting section of the Construct manual:

Part 12

When you're ready to continue, head on to the next part at Learn JavaScript in Construct, part 12: Modules!

  • 3 Comments

  • Order by
Want to leave a comment? Login or Register an account!
  • How can I pick an instance by an instance variable?

    • Just in case this is still relevant (for anyone with the same question): check out the fairly new example titled "Generator Function" for one way; but using generator functions is not required, you can just do that too:

      for (const inst of runtime.objects.SomeObjectType.instances())

      {

      if (inst.instVars.SomeInstanceVariable === 42) {...}

      }

  • does not help