Hi! I’m coming from Unity and getting a little lost while learning PlayCanvas UI and scripting, so I figured I’d post to see what I’m doing wrong. I’m a fairly experienced C# user but not a very experienced JavaScript user.
I’m building a little Nintendo-controller-style ‘d-pad’ out of UI buttons to make it possible to move the player character on a mobile device. I’ve got four buttons: up, down, left, and right.
In Unity, I’d build this by writing one script to move the player in a direction (i.e. a vector3), attaching that same script to each of the four buttons, and then setting that direction value in the inspector for each button. This way I have a nice, simple little reusable script! In PlayCanvas when I try to do the same, the player moves in every button’s direction value at the same time. It’s like the scripts are all firing at once (or there’s just one script that fires any time any button is pressed).
GamepadButton.attributes.add("direction", {type: "vec3", default: [0,0,0], title: "Direction to move"});
GamepadButton.attributes.add("player", {type: "entity", default: "", title: "Player"});
var isButtonPressed = false;
// initialize code called once per entity
GamepadButton.prototype.initialize = function(dt) {
var self = this;
// console.log(self.player);
this.entity.element.on('mousedown', this.onPress, this);
this.entity.element.on('mouseup', this.onRelease, this);
};
GamepadButton.prototype.update = function(dt) {
if (isButtonPressed) {
GamepadButton.prototype.move(this.player, this.direction);
}
};
GamepadButton.prototype.onPress = function (event) {
self.isButtonPressed = true;
};
GamepadButton.prototype.onRelease = function (event) {
self.isButtonPressed = false;
};
GamepadButton.prototype.move = function (player, direction) {
var rb = player.rigidbody;
rb.applyForce(direction);
};
I figure I could just create one big button input script and have it handle all the directional buttons, or create one separate script per button – and I’d be fine doing that if it’s just how things are done in PlayCanvas – but I’d also like to know why my way of doing things isn’t working, because I have a feeling it’s my understanding of JavaScript and maybe var/prototypes that is failing me here. If I had to make a guess, I’d say that every button is using that same isButtonPressed variable or something like that, and I’d love to know how to make that not happen.
Thanks so much in advance to anyone who can help!