Help moving turret shoot lasers

Hi all,

My situation is that I have a turret moving back and forth across the north wall in a square room. I’d like it to shoot out a short laser beam straight out every so often, maybe every 2-3 seconds, from wherever it is at the time. I’ve created the laser shot prefab (it’s a LineRenderer) and used a script online that makes the laser move forward immediately at runtime, but the turret moves away from it (and never de-spawns). How can I:

  • Ensure that the laser will spawn at the exact spot on my turret? I assume I attach an empty and invisible game object to where I want it to spawn (which will also move with the turrent), and use that, right? That I think I have correct.

  • Make sure the laser always moves in whatever way the turret is facing? I don’t plan on having the turrets turning DURING the game, but I’d like to be able to take the turret (and laser beam shot) I’ve made, duplicate it, move it to another wall, facing a different direction, and still have the laser move outwards from it.

  • Kill off the laser either when it hits the opposite wall, or flies far enough out of bounds?

  1. Create a reference Transform as a child of you laser turret.
  2. Spawn your laser shot using the reference’s position and rotation.
  3. Make sure the laser has a collider and
  4. Destroy the laser when it hits something (after doing damage if it hits something you want to damage).

To shoot every 2-3 seconds you would use Time.time.

    var spawnPos : Transform;
var laser : LineRenderer;
private var spawnTime : float = 2;

function Start () {

spawnTime = Time.time + 2;

}

function Update () {
	
	if(Time.time > spawnTime){
		spawnTime = Time.time + 2;
		 var clone : LineRenderer;
        clone = Instantiate(laser, spawnPos.position, transform.rotation);
    		
}
}

I’m not sure if the code works. I haven’t tested it yet, but if you come up with any errors ask me. Set spawnPos to the empty game object you want it to spawn from and Laser to you’re laser line.