Hello i am new to playcanvas and in need to create an fps game where i can change weapons using the scroll mouse wheel. However, i can’t seem to see lessons and codes for that.
i appreciate any kind of help
Here is an example script
var WeaponScroll = pc.createScript('weaponScroll');
WeaponScroll.attributes.add("time", {
type:"number"
});
// initialize code called once per entity
WeaponScroll.prototype.initialize = function() {
this.selectedWeapon = 0;
this.selectWeapon();
// listen for mouse scroll events
this.app.mouse.on(pc.EVENT_MOUSEWHEEL, this.onMouseScroll, this);
};
// update code called every frame
WeaponScroll.prototype.update = function(dt) {
};
// update code called every frame
WeaponScroll.prototype.onMouseScroll = function(e) {
let previousSelectedWeapon = this.selectedWeapon;
// Scroll Up
if(e.wheel > 0) {
if(this.selectedWeapon >= this.entity.children.length - 1) {
this.selectedWeapon = 0;
} else {
this.selectedWeapon++;
}
}
// Scroll Down
if(e.wheel < 0) {
if(this.selectedWeapon <= 0) {
this.selectedWeapon = this.entity.children.length - 1;
} else {
this.selectedWeapon--;
}
}
// Check and see if it is the same weapon
if(previousSelectedWeapon != this.selectedWeapon) {
this.selectWeapon();
}
};
WeaponScroll.prototype.handleOnKeyDown = function(e) {
if(e.key > pc.KEY_0 && e.key < pc.KEY_9) {
// get numerical value
var numKeyVal = e.key - pc.KEY_0;
var numWeapons = this.entity.children.length;
if(numKeyVal <= numWeapons) {
this.selectedWeapon = numKeyVal -1;
this.selectWeapon();
}
}
};
// Select Weapon
WeaponScroll.prototype.selectWeapon = function() {
let i = 0;
this.entity.children.forEach( weapon => {
if(i === this.selectedWeapon) {
weapon.enabled = true;
} else {
weapon.enabled = false;
}
i++;
});
};
4 Likes
Thank you very much for the example script. ill try my best to work on it
1 Like
@Kwangbae_IZONE If you would like to see a example of the script used above and maybe some other useful scripts for your project you can have a look here.
3 Likes