I’ve been wracking my brains around a design I want to add into my top down 2D game in Unity, but I cannot find a good approach.
I have a duplicator box, and a bullet travelling towards it.
Bullet Entering Box
… upon hitting/passing through/leaving the box, two bullets are spawned whose offsets have slightly moved from the original bullets path.
Two Bullets leaving box
The behaviour is also that should the bullet hit the duplicator box from a different direction, it will still spawn in the original path/direction.
One bullet entering box from an angle
Two bullets leaving box from the same angle
Asking here as I have a feeling there maybe a really simply way to do this and I’ve gone a very overcomplicated approach. Any suggestions?
I have already got this working slightly but its bad. I first grab the path/direction of the bullet (on the bullets class itself), instantiate a new bullet, and move the offset of both based on the path of travel.
public float offsetDistance = 0.1f; // Adjust this value to set the offset distance
void OnTriggerExit2D(Collider2D other)
{
Rigidbody2D rb = other.GetComponent<Rigidbody2D>();
rb.velocity = Vector2.zero;
DuplicateObject(other.gameObject);
this.GetComponent<BoxCollider2D>().enabled = false;
}
void DuplicateObject(GameObject originalObject)
{
GameObject newObject = Instantiate(originalObject, originalObject.transform.position, originalObject.transform.rotation);
Rigidbody2D originalRb = originalObject.GetComponent<Rigidbody2D>();
Rigidbody2D newRb = newObject.GetComponent<Rigidbody2D>();
if (originalRb != null && newRb != null)
{
newRb.velocity = originalRb.velocity;
newRb.angularVelocity = originalRb.angularVelocity;
// Get the normalized direction of travel
Vector2 directionOfTravel = originalObject.GetComponent<BulletController>().directionOfTravel;
// Calculate the new position with the offset
Vector2 offset = directionOfTravel * offsetDistance;
Vector2 newPosition = originalRb.position + offset;
// Apply the new position
originalRb.position = newPosition;
}
}
Jack Marshall is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.