So basically I wanted to make a game where you take control of a pirate on a boat that tries to avoid cannonballs shot at him.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Projectile : MonoBehaviour { public float speed;
private Transform player;
private Vector2 target;
void Start(){
player = GameObject.FindGameObjectWithTag("Player").transform;
target = new Vector2(player.position.x, player.position.y);
}
void Update(){
transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
}
void OnTriggerEnter2D(Collider2D other){
if(other.CompareTag("Player")){
DestroyProjectile();
}
}
void DestroyProjectile(){
Destroy(gameObject);
} }
I used this code to make projectiles go after the player but I’m not sure how do I make them keep moving forward after reaching their destination. I also want them to destroy themselves after going out of the map.