How to access a body's custom properties from within Phaser

General discussion about the R.U.B.E editor
Post Reply
bvargish
Posts: 26
Joined: Fri Oct 02, 2015 4:17 pm

How to access a body's custom properties from within Phaser

Post by bvargish »

This was initially a question, but I figured it out so I'm posting the answer for anyone else who needs it.

1. Create custom properties as explained at https://www.youtube.com/watch?v=nCp-EK_IICA

2. Load your scene into Phaser as explained at https://www.youtube.com/watch?v=_QqKMv6I2hc

3. Access your custom properties with levelScene.getBody(name).data.customProperties (not data.m_userData as I expected), which is an array of objects.

Getting the value of a specific property isn't as straightforward as something like data.customProperties.propertyName, so I wrote a function to get the values:

Code: Select all

function getProp(body, key) {
	var arr = body.data.customProperties;
	for (var i = 0; i < arr.length; i++) {
		console.log(arr[i]);
		if (arr[i].name == key) {
			console.log(arr[i].int);
			return arr[i].int;
		}
	}
}
I'm only dealing with properties with int values, so if you are dealing with any of the other types you would need to update this function.

Hope someone finds this helpful!
Post Reply