Hi.
I have this code here
GameObject flash = Instantiate(muzzleFlash, position, rotation) as GameObject;
and I’m trying to make it spawn the flash(MuzzleFlash) at the position and rotation of the bulletSpawn gameObject I have at the end of the barrel on my weapon.
but unfortunately I can’t figure out how to change the rotation to something random.
Meaning that it rotates the X to something random.
I hope that made sense…
The old-and-good-but-no-more-available FPS Tutorial used an interesting approach: instead of instantiating the muzzle flash every shot (what allocates memory), the muzzle flash was an object childed to the gun and with its renderer disabled. When shooting, the mesh was rotated randomly about its local Z axis and the renderer was enabled for just one frame. You could use the same trick with this code, which should be part of the weapon script:
public var muzzleFlash: Transform; // drag the muzzle flash object here
private var muzzle = false; // muzzle flash enabled last frame?
function Start(){
// make sure the muzzle flash is initially disabled:
muzzleFlash.renderer.enabled = false;
}
function TurnOnMuzzle(){
// rotate the muzzle flash randomly about Z:
muzzleFlash.Rotate(0, 0, Random.Range(0, 90));
muzzleFlash.renderer.enabled = true; // turn on muzzle flash
muzzle = true; // tell the code to turn it off next frame
}
function TurnOffMuzzle(){
if (muzzle){ // if muzzle flash enabled last frame...
muzzleFlash.renderer.enabled = false; // turn it off
muzzle = false;
}
}
TurnOnMuzzle must be called when you shoot - after checking ammo, shot interval etc. (flashing when you have no ammo is embarrasing…). Shooting or not, you must call TurnOffMuzzle every Update before doing anything in this script: this ensures that the muzzle flash lasts for just one frame:
function Update(){
TurnOffMuzzle(); // call this before anything in Update!
// rest of Update
}
try something like this:
GameObject flash = Instantiate(muzzleFlash, position, rotation.x, Random.Range(1, 360), rotation.z) as GameObject;
i have not tried this code because i do not have unity installed in this pc, though im pretty sure something like that should do the trick. hope it helps