I’m making a space shooter akin to asteroids, but with different weapons. One is homing bullets. On the homing bullet prefab, I have a 2d box collider for when the bullet hits an asteroid and a script for moving the bullet and destroying it once it has hit an asteroid. I also have a child object on the prefab that holds a circle collider and script to detect nearby asteroids. I need them to act independently, otherwise the bullet will destroy itself when the circle collider on the child object collides with an asteroid, when that’s what I want the box collider to do.
I’ve attached an image of the bullet.
Here’s the order of things I need to happen to make the bullet behave how I intend:
Instantiate bullet (Working)
Move bullet forward (Working)
Detect asteroid in path and assign “target” (Working when “Destroy” function is commented out)
Home-in on target (sort of working, but that’s a different issue)
Collide with asteroid and destroy bullet prefab (Destroys itself when circle collider hits, not when box collider does)
I’ve tried this after looking at another thread on Colliders. However, when I enter this code into monobehavior it says “Property collider has been depreciated. Use GetComponent() instead”.
Is this because of my version of Unity?
When I do try to use GetComponent it says that the “==” operator can’t be applied to operands of type “Collider2D” and “Type”.
I know this is not exactly what you want, but i believe its a better solution. put this on your bullet prefab and you can remove the circle collider and the code regarding it. this will move the bullet towards the asteroid if its within a certain distance
using UnityEngine;
public class Example: MonoBehaviour
{
private Transform target; //asteroid
public float certainDistance= 8;
public float speed; // speed in which the bullet moves towards the asteroid
void Start ()
{
target = GameObject.FindGameObjectWithTag("Asteroid").GetComponent<Transform>();
}
void Update ()
{
// if the distance between the bullet and the asteroid is less than 8
if (Vector2.Distance(transform.position, target.position) < certainDistance)
{
// move bullet towards object
transform.position = Vector2.MoveTowards(transform.position, target.position,
speed * Time.deltaTime);
}
}