Today’s challenge was to implement a Homing projectile!
To implement this feature, I had to go through many trials and errors. I basically know how to instantiate projectiles that go up but to have them rotate towards an enemy? I am inexperienced with this.
The challenge’s objective is to implement a new rare power-up that will enable the player to shoot homing projectiles. The first thing I did was to customize a current power-up image and make it it's own.
I did not know what to name the power-up, so I just came up with something so random! Why not call it “Eat This!” So the enemies can have a load of “eat this!” to your face, man! *chuckles* My humor is not great lol.
I imported the image into Unity and added the essential components that make up a power-up.
I also created a simple-looking missile sprite to represent the new projetile.
What I Learned
To have the projectiles rotate towards the enemy is a concept I knew about but hardly practiced.
I learned about the Cross Product and how it takes two vectors for a result of a third. This, with the rigidbody angular velocity of the missile equal to the negative rotation amount and times the speed, results in the logic to rotate towards the enemy. We then grab the reference to the rigid body's velocity to equal to the missiles transform up times the speed.
//Distance between the enemy and the missile
Vector3 direction = (Vector2)enemyInstance.transform.position — _rigidBody.position;//Reference the direction vector with a vector that will transform the missile upwards in the z axis. This will give us the third vector.
float rotateAmount = Vector3.Cross(direction.normalized, transform.up).z;//Grab the missiles rigidbody component to access its angular velocity. We need to equal it to the third vector times the rotation speed of the missile.
_rigidBody.angularVelocity = -rotateAmount * _rotateSpeed; //
Thanks to Brackey’s for this one. It’s a simplified version of the first attempts I had going at first on my own.
I also had to implement the logic for the homing missile to search for the closest enemy. I grabbed a reference to all enemy game objects active on the scene by using the enemy tag. I then grabbed their transform component and figure out which enemy is closest to the missile projectile. And that is all.
We now have homing missiles!
I learned a lot from this challenge. It was fun with lots of hair pulled out! lol.
That is all for today's challenge! Thank you for your time!