[Solved] Adding Script to Projectiles

Before watching how the course gets rid of projectiles that exited the gamespace or how to give the projectiles velocity, I tried it myself by adding a script to the projectile itself. This worked fine, however for the sake consistancy, I added the rigedbody2D to the projectile and added the velocity in the playerController script.

I did keep the option to destroy the projectile in the projectile’s script. Basically, I check if the projectile left the screen, if so, it destroys itself. This is the code I used:

void Update () {
		float distance = transform.position.z - Camera.main.transform.position.z;
		Vector3 ceiling = Camera.main.ViewportToWorldPoint(new Vector3(0,1,distance));
		if (this.transform.position.y > ceiling.y){

Before changing the velocity to the playerController script, I simply added a public accessable speed of the projectile:

public float speed = 10f;

and I added this line to the update() function:

this.transform.position += Vector3.up * speed * Time.deltaTime;

I was wondering if this is a better structure, worse, or if it’s just another way to achieve the same goal. My main reason to keep the Destroy command at the projectile’s script, is that I want to be able to make enemies spawn out of the screen, moving inwards. This way the Shredder won’t destroy the enemies.

1 Like

Nice solution!

I don’t think that this structure is worse than the one showed, actually it should be better performace wise since it don’t depends on collision detection. If I were to redo this game I’d probably just add a timer to the Destroy(Target Object, float TimeUntilDestroy) method and call it from the Start() within the bullet script or even when I instantiate the bullet (from the enemy or player prefab).

1 Like

I did the same here. I like it because I think it makes the game more flexible. You could add different shot types more easily as the behaviour of the shot is tied to the shot object itself…

Privacy & Terms