Hello, could someone help me? I have this cube which uses a script to change material when the player presses the A key, the problem is that I can’t get the material to hold when the A key is released, releasing the key returns to the original material. What is the problem?
The code:
var KeyboardHandler = pc.createScript('keyboardHandler');
KeyboardHandler.attributes.add('redMaterial', {
type: 'asset',
assetType: 'material'
});
KeyboardHandler.attributes.add('whiteMaterial', {
type: 'asset',
assetType: 'material'
});
// initialize code called once per entity
KeyboardHandler.prototype.initialize = function() {
// Use on() to listen for events on the keyboard device.
// Arguments are:
// 1) The event name to listen for
// 2) The callback function to call when the event fires
// 3) (optional) The value to use for 'this' in the callback function
this.app.keyboard.on(pc.EVENT_KEYDOWN, this.onKeyDown, this);
this.app.keyboard.on(pc.EVENT_KEYUP, this.onKeyUp, this);
};
/*
* Event handler called when key is pressed
*/
KeyboardHandler.prototype.onKeyDown = function (event) {
// Check event.key to detect which key has been pressed
if (event.key === pc.KEY_A && this.redMaterial) {
this.entity.model.meshInstances[0].material = this.redMaterial.resource;
}
// When the space bar is pressed this scrolls the window.
// Calling preventDefault() on the original browser event stops this.
event.event.preventDefault();
};
/*
* Event handler called when key is released
*/
KeyboardHandler.prototype.onKeyUp = function (event) {
// Check event.key to detect which key has been pressed
if (event.key === pc.KEY_A && this.whiteMaterial) {
this.entity.model.meshInstances[0].material = this.whiteMaterial.resource;
}
};
/*
* Event handler called when key is pressed
*/
KeyboardHandler.prototype.onKeyDown = function (event) {
// Check event.key to detect which key has been pressed
if (event.key === pc.KEY_A && this.whiteMaterial) {
this.entity.model.meshInstances[0].material = this.whiteMaterial.resource;
}
// When the space bar is pressed this scrolls the window.
// Calling preventDefault() on the original browser event stops this.
event.event.preventDefault();
};
/*
* Event handler called when key is released
*/
KeyboardHandler.prototype.onKeyUp = function (event) {
// Check event.key to detect which key has been pressed
if (event.key === pc.KEY_A && this.redMaterial) {
this.entity.model.meshInstances[0].material = this.redMaterial.resource;
}
};
The proyect:
https://playcanvas.com/project/690542/overview/test-segundero