[SOLVED] Shooting code assitance

Hi! I am making an fps game I’ve tried several times and I don’t know if my script is wrong or something else.

Code:

var Firebullet = pc.createScript('firebullet');

Firebullet.attributes.add('bulletEmitter', {
  type: 'entity',
});

// initialize code called once per entity 
Firebullet.prototype.initialize = function() {

};

// update code called every frame 
Firebullet.prototype.update = function(dt) {

  if (this.app.keyboard.wasPressed(pc.KEY_SPACE)) {

    var bulletAsset = this.app.assets.get(107034286); //gets arrow from window
    var bulletInstance = bulletAsset.resource.instantiate(); //makes arrow appear
    this.entity.addChild(bulletInstance); //makes arrow a child of root

    var bulletPosition = this.bulletEmitter.getPosition();

    bulletInstance.rigidbody.teleport(bulletPosition);

    this.force = new pc.Vec3();
    this.bulletDirection = this.force.copy(this.entity.forward);
    this.bulletDirection.scale(1000);

    bulletInstance.rigidbody.applyForce(this.force);
    
  }
};

@Marstheplanet Can you describe what is going wrong with your project? Is it that you are getting errors or does the script not do what you want it to do? There have been several topics related to this on the forum. Some could take a better look if you shared your project.

1 Like

Hi thank you for the reply! The problem is the bullet is not moving and just floating in one area. I need to spawn and shoot. I did try following the other threads and I’m still having a hard time.

This is the hierarchy that I have right now:

@Marstheplanet Does your bullet have a collision and rigid body? Also, in the rigid body you will need to set the rigid body to Dynamic. I am not sure about the force applied above.

Shoot.prototype.shoot = function(dt){
    // Clone the bullet as specified by the attribute
    var bullet = this.bullet.clone();
    // Add it to the game 
    this.app.root.addChild(bullet);

    var player = this.entity;
    // Its force is in the direction the player is facing 
    this.force = new pc.Vec3();
    this.force.copy(player.forward);
    this.force.scale(this.power);
    
    var pos = player.getPosition();
    var direction = player.forward; 
    // Add it a little further if the player is already going fast
    //pos.add(direction.scale(5 + player.rigidbody.linearVelocity.length() * 0.01));
    
    bullet.setPosition( pos );
    var bulletRotation =  player.getRotation();
    bullet.setRotation( bulletRotation );
    bullet.rotateLocal(90,0,0);
    
    bullet.enabled = true; //Must enable after setting position!
    
    bullet.rigidbody.applyImpulse(this.force);
};

Here is some code from something that I have done. Maybe it will apply. THE ROTATION ABOVE MAY NEED ADJUSTING>

Hi sorry for the late reply but I was able to figure out the shooting script thank you so much for offering to help!

hi, how did you fix it?