- Home /
Instantiate GameObject on GUI Button click and rotate the object.
Hey everyone I am trying to figure out how to instantiate an object whose rotation initially matches the direction my player gameobject is facing and then performs a 90 degree rotation (similar to an animation). I am making a 2d Dungeon Crawler and want to use prefabs of the weapons with individual stats and colliders that can be found throughout the game rather than setting up different animations for each weapon.
Below is the pseudo code for what I am trying to accomplish:
public void Attack()
{
//array of swords public GameObject[] swords;
//sword prefab based on array variable ie swords[0] = starter sword.
//equipped sword int = 0
//instantiate swords[equipped sword] at player direction of travel. rotate from 0 to -90 at speed. detect collision and deal damage. destroy gameobject.
Debug.Log ("Attacking");
}
I know how to set up the array and assign the prefab being spawned from the array I just dont know how to set the rotation to initially match the direction my player is facing and then make it rotate 90 degrees to simulate a sword swing.
Turns out hinged joints are an amazing thing and dont require alot of physics to function (I have been avoiding using any physics in my game because of how I generate my levels). For anyone looking for a similar solution though I recommend looking into the different types of joints available.
Answer by unity_BGmJcdED5Dqjfw · May 13, 2018 at 07:44 PM
One thought I had was after the instantiation of the gameobject make a while statement:
while("spawnedprefab".rotation.z < 90; "spawnedprefab".rotation.z++)
{
yield return new WaitForSecond(0.1f);
}
which should in theory force a "smooth" rotation of the object and I could adjust the <90 and rotation.z++/rotation.z-- portion to relate properly to the direction the character is facing.
I dont know if there is an easier way to accomplish this however.
Your answer
Follow this Question
Related Questions
2D Array of GameObjects... 1 Answer
2D Array's 1 Answer
Multiple Fire Points 2 Answers
Instantiating a gameObject in an array is not working for me 1 Answer