I want to know how I can fix my script to be able to instantiate my project from the tip of my cannon object, below is my complete script:
@serializable()
enableMobileInput: boolean = true;
@serializable()
enableDesktopInput: boolean = true;
//@nonSerialized
@serializable()
vrSide: XRHandedness | "any" = "any";
@serializable()
fireRate: number = 0.1;
@serializable(Object3D)
raycastReference?: Object3D;
@serializable(Animator)
gunAnimator?: Animator;
@serializable()
fireAnimation: string = "Fire";
@serializable(AudioSource)
fireSound?: AudioSource;
@serializable(ParticleSystem)
muzzleFlash?: ParticleSystem;
@serializable(ParticleSystem)
ejectShell?: ParticleSystem;
@serializable(ParticleSystem)
impactEffect?: ParticleSystem;
/////
@serializable(AssetReference)
arrowPrefab?: AssetReference;
@serializable(AudioSource)
sound?: AudioSource;
/////
@serializable(Vector3)
startPosition?: Vector3;
@serializable(Object3D)
positionReference?: Object3D; // Reference to the object which position you want to use
private onMouseClick = (event: MouseEvent) => {
if (!document.pointerLockElement && event.target !== this.context.renderer.domElement) return;
if (isMobileDevice()) return; // ignore desktop input on mobile
if (event.button !== 0) // if not the LMB or primary, abort
return;
this.fire();
const myPosition : Vector3 = new Vector3(0, 0, 0);
//const myPosition : Vector3 = new Vector3(this.startPosition);
//this.myObjectReference = this.gameObject.position.clone();
// Instantiate the object at the position of 'positionReference'
// Adjust the position if necessary, for now it inherits the position from 'positionReference'
// instance.position.set(...) if you need to adjust the position further
//const myPosition : Vector3 = myObjectReference;
this.shoot(myPosition, myPosition);
}
/**
* shoot an arrow
* @param from position to shoot from
* @param vec direction to shoot (not normalized)
*/
private async shoot(from: Vector3, vec: Vector3) {
if (!this.arrowPrefab) return;
const instance = await this.arrowPrefab.instantiate({ parent: this.context.scene });
const force = Math.pow(vec.length() + .5, 2);
const dir = vec.clone().normalize();
if (instance) {
instance.position.copy(from);
instance.lookAt(dir.clone().add(from));
instance.visible = true;
const rb = instance.getOrAddComponent(Rigidbody);
rb.isKinematic = false;
rb.autoMass = false;
rb.mass = .05;
this.sound?.stop();
this.sound?.play();
// workaround Rigidbody not yet created in the physics engine (it gets created in onEnable)
//wait delayForFrames(1);
rb.applyImpulse(dir.multiplyScalar(force), true);
}
}