- Home /
The question is answered, right answer was accepted
How to change the force for seconds using a Coroutine?
2D C#
I have a simple and probably very stupid question, which is why I apologize for any possible littering of the forum.
How to make the object's ("Player") forceFly increase by 1000 when it hit the object: "BrownWorm" (in OnCollisionEnter2D), for 5 seconds, then return to normal?
My main problem is the lack of assigned value to fireFly, because I want to specify it in the inspector.
I know that to return after 5 seconds I should add IEnumerator and yield, but I do not know know how to start this power change.
I would also be grateful if someone in this example would explain how it works,
My script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBehaviour : MonoBehaviour {
public Transform mesh;
public float forceFly;
private Animator animatorPlayer;
private float currentTimeToAnim;
private bool inAnim;
// Use this for initialization
void Start () {
animatorPlayer = mesh.GetComponent<Animator>();
this.gameObject.GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0)) {
inAnim = true;
GetComponent<Rigidbody2D> ().velocity = Vector2.zero;
GetComponent<Rigidbody2D> ().AddForce (new Vector2 (0, -1) * forceFly);
}
if (inAnim) {
currentTimeToAnim += Time.deltaTime;
if (currentTimeToAnim > 0.4f) {
currentTimeToAnim = 0;
inAnim = false;
}
}
animatorPlayer.SetBool ("callFly", inAnim);
}
void OnCollisionEnter2D(Collision2D coll){
if (coll.gameObject.tag == ("Enemy"))
Destroy (gameObject);
}
}
Answer by polan31 · May 08, 2018 at 08:13 AM
Problem solved by myself. I added some variables false, true and everything works.
Answer by bhavinbhai2707 · May 05, 2018 at 03:02 PM
Simple!!
public float forceFlyAdd;
public bool isFaster;
void OnCollisionEnter2D(Collision2D coll){
if (coll.gameObject.tag == ("Player"))
isFaster = true;
Debug.Log ("Speed Powerup");
Destroy (gameObject);
PlayerBehaviour theSpeed = coll.gameObject.GetComponent<PlayerBehaviour> ();
float temp = theSpeed.forceFly;
theSpeed.forceFly = forceFlyAdd;
StartCoroutine ("WaitTime", theSpeed);
theSpeed.forceFly = temp;
}
public IEnumerator WaitTime(PlayerBehaviour playerForceFly) {
yield return new WaitForSeconds (5);
isFaster = false;
}
}
I made the changes near startCoroutine!!