- Home /
The question is answered, right answer was accepted
Coroutine - transform for every frame for duration?
Hi, newbie here. I'm working on a shield mechanic for my 2D shooter. I have it set up so on a button press, it brings a shield from off screen onto the player. It's supposed to stay on top of the player for 2 seconds, and then go back off screen.
I'm using a coroutine, and it almost works. Right now, if I press my shield button, the player just plops out the shield, and it stays at the player's location and rotation where the button was pressed, and then goes back off screen after 2 seconds.
Is there a way to copy the player's position and rotation every frame until the 2 seconds are up?
Here's my script:
public class PlayerShield : MonoBehaviour
{
public Transform player;
float shieldDelay = 5f;
float cooldownTimer = 0;
void Update()
{
cooldownTimer -= Time.deltaTime;
if (Input.GetButton("Shield") && cooldownTimer <= 0)
{
StartCoroutine(ShieldStart());
cooldownTimer = shieldDelay;
}
IEnumerator ShieldStart()
{
transform.position = player.transform.position;
transform.rotation = player.transform.rotation;
yield return new WaitForSeconds(2);
transform.position = new Vector3(2000, 2000, 0);
}
}
thanks :)
"Parent" it to player object or directly copy its position and rotation.
transform.parent = player;
yield return new WaitForSeconds(2);
transform.parent = null;
gameObject.SetActive(false);
Or
float duration = 2f;
float timer = 0f;
// Custom frame by frame update
while(timer < duration){
timer += Time.deltaTime;
transform.position = player.position;
transform.rotation = player.rotation;
yield return null; } @FlabbyGabby