-3- Unity 3D: Shooting Missiles Towards Enemy Position.
1. Add Player.cs Script.
public class Player : MonoBehaviour
{
public Missile missilePrefab;
public Transform firePoint;
//Add
public GameObject enemy;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
FireMissile();
}
}
void FireMissile()
{
//Add.
//Determine the direction of the enemy.
var enemyDir = (enemy.transform.position - transform.position).normalized;
//Look directly at the enemy direction.
var lookRotation = Quaternion.LookRotation(enemyDir);
firePoint.rotation = lookRotation;
//Missile Instantiate.
Instantiate(missilePrefab, firePoint.position, firePoint.rotation);
}
}
2. Set Up the Player Gameobject.
Drag Enemy Gameobject to Player Gameobject.
Conclusion
Now, when the player fires a missile, it will fly towards the enemy. Use this feature to enhance the fun of your game!
