- Home /
Move Overlapbox/GameObject depending on Parent
So I've been making a 2D Top-Down RPG, and am currently figuring out how to do the combat. Using tutorials, I chose to do this:
Collider2D[] enemiesToDamage = Physics2D.OverlapBoxAll(attackPos.position, new Vector2(attackRangeX, attackRangeY), 0, whatIsEnemies);
for (int i = 0; i < enemiesToDamage.Length; i++)
{
enemiesToDamage[i].GetComponent<EnemyHealthManager>().TakeDamage(damage);
}
However, I would like to move the "hitbox" (called "AttackPos"), depending on the direction the character is looking. How can I put this into my scripts? I also made a string called "direction" on my PlayerMovement script, but I don't know how to proceed.
Also, how can I rotate the OverlapBoxAll when looking to the left/right?
Sorry for any English mistakes and if this is a stupid question, I'm stuck :(
Answer by wertyq · Dec 14, 2020 at 04:31 AM
You can rotate the parent in the PlayerMovementScript by using Quaternion.LookRotation().
Do you know how I can change the position of the Empty Gameobject? If I could learn how to move it by, i.e., 5pixels to the right, and rotate it, that would help me a lot
Is the empty gameobject the parent of your hitbox and a child of your player?
I don't know what you mean by "parent of your hitbox"
The empty gameobject is a child of my player
The hitbox is basically the position of this empty gameobject, with an attackRange I can set myself
I just need to know how to move that empty gameobject relative to my player :(
Answer by wertyq · Dec 14, 2020 at 05:14 AM
Great! So, from your PlayerMovement script, you can access your child Game Object by using
void Start()
{
GameObject childGameObject = transform.Find("Name of your child game object");
}
The code below this goes under Update(), might be a good idea to put this inside your if (movement != Vector2.zero) block
if (movement.x > 0)
{
childGameObject.transform.localPosition = new Vector3 (5,0);
}
if (movement.x < 0)
{
childGameObject.transform.localPosition = new Vector3 (-5,0);
}
if (movement.y > 0)
{
childGameObject.transform.localPosition = new Vector3 (0,5);
}
if (movement.y < 0)
{
childGameObject.transform.localPosition = new Vector3 (0,-5);
}
Also, might want to consider changing your EmptyGameObject name to something like, I don't know, AttackPosHolder. So, instead of childGameObject, its easier to read your code in the future by using the name attackPosHolder.
Your answer
Follow this Question
Related Questions
Following another object's position/rotation like parent/child relationship? 4 Answers
parent Transform.position unexpected behaviour when changing position 1 Answer
Controlling parent by Inputs 1 Answer
Transform position in editor confusion (screenshot examples) 1 Answer
Moving parent to position of child 0 Answers