- Home /
How to make a projectile keep moving forward and then destroy itself when out of the map
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.
Ok I just decided to destroy the projectile after some time since it'll fly out of the player's view anyways so I added this:
private float destroyTime = 4;
void Update(){
Destroy(gameObject, destroyTime);
Answer by kwr800 · Feb 23, 2021 at 09:47 PM
Vector3 motion;
void Start()
{
Vector3 sourceToDestination = player.position - transform.position;
motion = sourceToDestination.normalized * speed;
}
Ok I added another vector and replaced the void Update with this :
void Update()
{
transform.position += motion * Time.deltaTime;
}
It seems to go in a line after achieving it's original destination but I still don't know how to make it disappear after going out of the map.
Do you have a map boundary? Like a box that is the boundary? If so you could add a collider on it and delete the object that enters if it has the tag "arrow"
I surrouded the map with 4 box colliders. Can you please explain in a bit more detail how to delete the objects that come into contact with them?
You can attach a script either to the boundaries or the objects, that use OnTriggerEnter, to detect a boundary. If the trigger's tag is set to boundary, destroy itself. For example, if you were to put a script on the object:
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Boundary"))
{
Destroy(gameObject);
}
}
Destroying it after some time works fine too, but I would recommend that you try the more solid solution. You never know what spaghetti you might have to end up untangling later down the line, when your bullets can't reach the other side of a long map.