- Home /
Help with Instantiate and parents
When I Instantiate an object, it does not spawn where the parent is, but where the parent first spawned. I have tried to find out a way to set the Instantiated object's parent, but I can't seem to figure it out. Thanks for any help.
void OnTriggerEnter2D (Collider2D shoot) {
Vector2 myTransform = player.transform.position - transform.position;
Rigidbody2D clone;
Vector3 offset = transform.position;
offset.x = -0.1f;
if (shoot.gameObject.tag == "Player") {
clone = Instantiate (bullet, offset, transform.rotation) as Rigidbody2D;
clone.velocity = transform.TransformDirection (myTransform * 2.5f);
}
}
Answer by seandolan · Feb 21, 2018 at 11:26 PM
What happens if you change it to the following?
Vector3 offset = new Vector3(-0.1f,0,0);
clone = Instantiate (bullet, transform.position + offset, transform.rotation) as Rigidbody2D;
Yes that fixed my problem, thanks! However, if my player is on the other side of the enemy shooting the gun, the bullet still comes out on the other side of the enemy. How would I go about fixing that?
Sorry I am not sure what you mean. You want the offset to be based off the direction the enemy is facing?
Yeah, I tried to apply this to the code, but that only managed to flip the sprite depending on which side the player was of it. Vector3 offsetLeft = new Vector3(-0.5f, 0f, 0f); Vector3 offsetRight = new Vector3(0.5f, 0f, 0f);
if (shoot.gameObject.tag == "Player" && facingRight == false) {
clone = Instantiate (bullet, transform.position + offsetLeft, transform.rotation) as Rigidbody2D;
clone.velocity = transform.TransformDirection (myTransform * 2.5f);
}
if (shoot.gameObject.tag == "Player" && facingRight == true) {
clone = Instantiate (bullet, transform.position + offsetRight, transform.rotation) as Rigidbody2D;
clone.velocity = transform.TransformDirection (myTransform * 2.5f);
}
}
void Update () {
moveX = enemy.velocity.x;
if (moveX < 0.0f) {
GetComponentInParent<SpriteRenderer>().flipX = false;
facingRight = false;
} else if (moveX > 0.0f) {
facingRight = true;
GetComponentInParent<SpriteRenderer>().flipX = true;
}
}
The offset needs to be based off the enemy's direction it is facing? I am more experienced with 3d in Unity. In 3d I use something like transform.TransformDirection(offset). I am unsure what it is in 2d though. $$anonymous$$aybe that will work anyway. I am not sure.