I’m making an FPS game, and my guns will have flashlight attachments, which I want to toggle with the C key. How do I do this? I already have the flashlight attached to the gun, but I don’t know how to get the code to work. Also, my gun won’t follow where I look, even though I add the gun to the camera as a child. Please help
Hi @asiangurberbaby and welcome,
For the flashlight to follow you it should be enough to add it as a child to the camera. That way it will update its position and rotation to match the camera.
For toggling on an off the flashlight you can do it easily in a script attached to it. Add this code in the update method:
if(this.app.keyboard.wasReleased(pc.KEY_C) === true){
this.entity.enabled = !this.entity.enabled;
}
@Leonidas I don’t know how to code in JavaScript, but I’m learning it in my freetime. I added the code you provided me with, but it didn’t work, which I’m assuming is because there is much more to the picture. All I have for the flashlight script is below.
var Flashlight = pc.createScript('flashlight');
if(this.app.keyboard.wasReleased(pc.KEY_C) === true){
this.entity.enabled = !this.entity.enabled;
}
Also, I think the engine is broken or something because in Hierarchy, I dragged the gun onto the camera, which should’ve added it as a child right? The gun still doesn’t follow where I look. Either it’s broken or I’m just really, really dumb.
Hi @asiangurberbaby!
You need to place the code inside the update function that you can find in a new script. The script need also be attached to an entity in your hierarchy. For this you need to add a script component to the entity.
Can you show a screenshot of it?
If it is correct what @Leonidas said, that should be okay, but I have experience earlier that this doesn’t work. I’m not sure anymore what the issue was or how to solve it.
I checked this with the first person sample project and it’s working as expected.
https://playcanvas.com/project/858687/overview/custom-first-person-controller
how do I add as a child?
Hi @Brent_Reddick and welcome! In the hierarchy of your scene (left panel of the editor) you can drag and drop an entity into another entity.