How to access a body's custom properties from within Phaser
Posted: Thu Dec 03, 2015 7:13 pm
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:
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!
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;
}
}
}
Hope someone finds this helpful!