Making an object "Flicker" every X seconds - c#

I need to make an object flicker every X seconds. So far I have the code for the actual flickering and it works great, however I need the flicker to come on for X seconds, then turning off, then come on for X seconds. Similar to turning a strobe light on (it flickers), then off.
I know something like invokeRepeating would work however the flickering relies on being in the FixedUpdate for it to run every frame.
For anyone wondering I'm actually trying to do something with image modulation and attention. Here is what I have so far:
public class scrFlicker : MonoBehaviour {
public SpriteRenderer sRen;
public float cycleHz; // Hz, the mesurement of cycles.
private float dtime = 0; // delta time
private Color alpha;
// Use this for initialization
void Start () {
sRen = GetComponent<SpriteRenderer>();
GetComponent<SpriteRenderer>().enabled = false;
alpha = sRen.color;
alpha.a = 0.4f;
sRen.color = alpha;
}
// Update is called once per frame
void FixedUpdate () {
startFlicker();
}
void startFlicker() {
dtime += Time.deltaTime;
float wave = Mathf.Sin((dtime * 2.0f * Mathf.PI) * cycleHz);
if(wave > 0.0f) {
GetComponent<SpriteRenderer>().enabled = true;
} else {
GetComponent<SpriteRenderer>().enabled = false;
}
if (wave == 0.0f) {
dtime = 0.0f;
}
}
}

You can create something like a timer below to manage the on and off time:
float toggletime;
void FixedUpdate () {
toggletime += Time.deltaTime;
if (toggletime < 2) // flicker will occur from 0-2 seconds
startFlicker();
else if (toggletime > 4) // nothing will occur between 2-4 seconds
toggletime = 0; // reset timer after 4 seconds have passed
}

"I know something like invokeRepeating would work however the flickering relies on being in the FixedUpdate for it to run every frame."
FixedUpdate is for Physics. Sure you can use it for other purposes but if they not physics related then it is not the primary purpose.
Invoke would actually do just fine, you have full control of it.
float timer = 2f;
bool isOn = false;
void Start()
{
Invoke("Method", timer);
}
void Method()
{
// you can change timer if needed
this.timer = Random.Range(0f, maxTimer);
this.isOn = !this.isOn;
Invoke("Method", this.timer);
}
void CancelMethodAndResetTimerForAnyReason()
{
CancelInvoke();
this.timer = Random.Range(0f, maxTimer);
Invoke("Method", this.timer);
}

Related

How do I smooth my slider value in unity?

I have a script which updates the slider value based on slowMotionTimeLeft, to decreaseslowMotionTimeLeft. I am using a for loop with a coroutine which has a delay of 1 second, like this:
IEnumerator DecreaseSlowMotionTime()
{
for(int i = 0; i < 5f; i++)
{
slowMotionTimeLeft -= 1f; // decrease slow motion
///<summary>
/// if slow motion time is less than or equal to 0 break the loop
/// </summary>
if (slowMotionTimeLeft <= 0f)
{
onSlowMotion = false;
break;
}
yield return new WaitForSecondsRealtime(1f); // delay
}
}
now I have a slider, I want to smoothly update that value based on slowMotiontimeLeft, but it is not smooth, it is updating every second like the coroutine, I tried to lerp the values but it does not work.
Here is the script:
// Slow Motion Bar
[Header("Slow Motion Slider Bar")]
[SerializeField] private Slider slowMoLeft;
[SerializeField] private float slowSliderSmoothSpeed = 0.125f;
// Other
private Player playerScript;
void Awake()
{
playerScript = FindObjectOfType<Player>();
}
void Update()
{
UpdateSlowMoSlider();
}
public void UpdateSlowMoSlider()
{
slowMoLeft.value = playerScript.slowMotionTimeLeft;
}
any tips of what can I do? do I need to update the coroutine timer to make wait 0.1 seconds?
I'd do it in Update:
// Remove the IEnumerator DecreaseSlowMotionTime(), instead add this, or if you already use Update() add the content of this method to Update()
public void Update()
{
if (slowMotionTimeLeft > 0)
{
slowMotionTimeLeft -= 1f * Time.deltaTime;
}
}
// Slow Motion Bar
[Header("Slow Motion Slider Bar")]
[SerializeField] private Slider slowMoLeft;
[SerializeField] private float slowSliderSmoothSpeed = 0.125f;
// Other
private Player playerScript;
void Awake()
{
playerScript = FindObjectOfType<Player>();
}
void Update()
{
slowMoLeft.value = playerScript.slowMotionTimeLeft;
}
You can make your code better:
Instead of updating your slowMotionTimeLeft once every second, you can do something like this:
IEnumerator DecreaseSlowMotionTime()
{
while (onSlowMotion)
{
// decrease slow motion without considering Time.timeScale
slowMotionTimeLeft -= Time.unscaledDeltaTime;
// if slow motion time is less than or equal to 0 break the loop
if (slowMotionTimeLeft <= 0f)
{
onSlowMotion = false;
}
// will execute again in the next frame
yield return null;
}
}
Then your slider will reduce smoothly and at a 1:1 time speed.
I know a another way
Just download DoTweenModuleUI and you are good to go
https://github.com/fisheraf/Stroids/blob/master/Stroids/Assets/Demigiant/DOTween/Modules/DOTweenModuleUI.cs
just save this script in any external plugins folder and use
yourimageName.DoFillAmout(TargetValue,Duration); That's it
Something like this imageSlider.DOFillAmount(perSecElixir / 10, 0.5f);

Unity infinite background change with transition

i have the infinite background set up with the tiling method which is moving from the right to the left, what i want to do is that if the player reaches an amount of score(like 1000), i want to change the background via a transition, like the next background will move in from the left to the right like the other one did, but when it moves in, it stays till the player reaches another amount of score(like 2000). Then it happens again but now with an other texture.
The current script looks like this:
public class BackgroundScroll : MonoBehaviour {
Material material;
public Material materialChange;
Vector2 offset;
public int xVelocity, yVelocity;
private float backgroundSpeed = 1f;
public static float speed = 10f;
private float speedUp = 0.1f;
private int changed = 0;
private void Awake()
{
material = GetComponent<Renderer>().material;
speedUp = 0.1f;
}
// Use this for initialization
void Start () {
changed = 0;
//offset = new Vector2(xVelocity, yVelocity);
StartCoroutine(Speed());
}
// Update is called once per frame
void Update () {
offset = new Vector2(xVelocity, yVelocity);
material.mainTextureOffset += offset * Time.deltaTime * backgroundSpeed;
BackgroundChange();
}
void BackgroundChange()
{
if (ScoreHandler.score >= 100 && changed == 0)
{
material.mainTexture = materialChange.mainTexture;
changed = 1;
}
}
IEnumerator Speed()
{
yield return new WaitForSeconds(20);
speed += speedUp;
backgroundSpeed += speedUp;
}
}
This line changes the background, but there is no animation or transition at all, it just changes it: material.mainTexture = materialChange.mainTexture;
So my question is that how can i change the background with an animation, so it slides it then it stays till the other one slides in and that stays. etc...

How to stop function after 1 second Unity 3D?

In my code, I am calling a Slow motion function when the player enter to a Trigger, but I want this function to stop after 1 second, I tried the code below but the slow motion didn't work. Do you have any idea?
Player Script:
public Rigidbody Ball;
public float Speed = 50f;
public TimeManager timeManager;
bool SlowOn;
bool ClickDone = false;
// Use this for initialization
void Start () {
StartCoroutine(SlowOff());
}
// Update is called once per frame
void FixedUpdate () {
if (!ClickDone){
if (Input.GetMouseButton (0)) {
ClickDone = true;
Ball.velocity = transform.forward * Speed;
}
}
}
private void OnTriggerEnter (Collider other) {
if(other.gameObject.CompareTag ("SlowMotionArea")) {
if (SlowOn) {
timeManager.DoSlowMotion();
}
}
}
IEnumerator SlowOff () {
yield return new WaitForSeconds(2.0f);
SlowOn = false;
}
TimeManager Script:
public float SlowDownFactor = 0.05f;
public float SlowdownLength = 2f;
public void DoSlowMotion () {
Time.timeScale = SlowDownFactor;
Time.fixedDeltaTime = 0.02f * Time.timeScale ;
}
There are a few problems with your code
You never set SlowOn to true so your line
timeManager.DoSlowMotion();
is never executed. Somewhere in your code you should call
SlowOn = true;
I'm guessing but it seems that you wanted to use that bool to prevent multiple calls of timeManager.DoSlowMotion()? In this case it should rather be something like
if(!SlowOn)
{
timeManager.DoSlowMotion();
SlowOn = true;
}
Why do you call StartCoroutine(SlowOff()); in your Start() method?
I guess you should rather remove that line and place it after
timeManager.DoSlowMotion();
StartCoroutine(SlowOff());
so the Coroutine is started everytime a SlowMotion starts.
It is not enough for the SlowMotion to stop to just set your SlowOn = false.
In your TimeManager you should rather store the original TimeScale and reset them in a second method:
public float SlowDownFactor = 0.05f;
public float SlowdownLength = 2f;
private float originalTimeScale;
private float originalFixedDeltaTime;
public void DoSlowMotion () {
// before changing store current values
originalTimeScale = Time.timeScale;
originalFixedDeltaTime = Time.fixedDeltaTime;
Time.timeScale = SlowDownFactor;
Time.fixedDeltaTime = 0.02f * Time.timeScale ;
}
public void ResetTimeScales()
{
Time.timeScale = originalTimeScale;
Time.fixedDeltaTime = originalFixedDeltaTime;
}
and than you also have to call that ResetTimeScales method from the player
IEnumerator SlowOff () {
yield return new WaitForSeconds(2.0f);
timeManager.ResetTimeScales();
SlowOn = false;
}
I guess you know that
yield return new WaitForSeconds(2.0f);
will also be affected by the changed Timescale so your SlowMotion currently would be longer than the expected 2 seconds namely 2 / SlowDownFactor = 40!
You could avoid this by using the Time.unscaledDeltaTime as a countdown like
private IEnumerator SlowOff()
{
// since your title actually claims you want to reset after 1 second
float timer = 1;
while (timer > 0)
{
timer -= Time.unscaledDeltaTime;
yield return null;
}
timeManager.ResetTimeScales();
SlowDown = false;
}

Changing the fire rate while button pressed

I have a 2D shooting game on Unity using C# now and I want to increase the fire rate of the ship for 5 seconds when it gets a power up item. It kinda works but when the ship gets the power up, the fire rate does not change until the button is released and pressed again. Is there a way to change the fire rate as soon as it gets the power up even while the button is being pressed? Also, the power up function is something that I came up with and if there is a better way to make the power up functions, that will be very helpful too. Thanks in advance :)
void Update(){
if (Input.GetKeyDown(KeyCode.Space)){
InvokeRepeating("Fire", 0.000001f, fireRate);
}
}
void PowerUp()
{
Upgrade = true;
timeLeft = +5f;
if (Upgrade == true)
{
fireRate = 0.1f;
}
if (timeLeft <= 0)
{
Upgrade = false;
fireRate = 0.5f;
}
}
You should pass an reference type to the Fire coroutine instead of a float fireRate.
Just wrap fireRate in a class should work:
class FireData
{
public float fireRate = 0.1;
}
Then in your script,
FireData fireData = new FireData { fireRate = 0.5f };
void Update(){
if (Input.GetKeyDown(KeyCode.Space)){
InvokeRepeating("Fire", 0.000001f, fireData);
}
}
void PowerUp()
{
Upgrade = true;
timeLeft = +5f;
if (Upgrade == true)
{
fireData.fireRate = 0.1f;
}
if (timeLeft <= 0)
{
Upgrade = false;
fireData.fireRate = 0.5f;
}
}
In Fire() coroutine, use this fireData.fireRate to get the fireRate.
By the way, I think your power up functions is good enough.
But the way of using coroutine is not correct.Don't call InvokeRepeating on the same function multiple times.
if (Input.GetKeyDown(KeyCode.Space)){
InvokeRepeating("Fire", 0.000001f, fireRate);
}
Instead, you should use a bool value to control when the fire will start.
if (Input.GetKeyDown(KeyCode.Space)){
fireData.Firing = true;
}
if(fireData.Firing)
{
InvokeRepeating("Fire", 0.000001f, fireRate);
}
Also remember to add a logic to stop firing via StopCoroutine.

How to constantly rotating with WaitForSeconds in update function - Unity

I am looking for a help with make a delay in Unity in Update function.
I created something like this below. The cube is moving rotates once and then is waiting > rotates once > waiting ....
And there is my question. How i can make cube rotates constantly for some time instead of once. For Example: Wait 2sec, rotating constantly 5sec, Wait 2sec, rota....
I thinked about replace
ForCube.transform.Rotate (10, 10, 10);
by rotating Animation. But I want create it with transform.Rotate. Is there any option to do this?
using UnityEngine;
using System.Collections;
public class Ruch : MonoBehaviour
{
public float speed = 5;
public GameObject ForCube;
bool work = true;
// Use this for initializat
void Start ()
{
ForCube = GameObject.Find ("Cube");
Debug.Log (ForCube);
}
// Update is called once per frame
void Update ()
{
if (work) {
StartCoroutine (WaitSome ());
}
}
private IEnumerator WaitSome ()
{
work = false;
yield return new WaitForSeconds (3f);
ForCube.transform.Rotate (10, 10, 10);
work = true;
}
}
At the moment it looks like to me you are using a StartCoroutine which will work fine, but if you want maybe a little more control over when to rotate and when to stop you can use the Time.deltaTime The time in seconds it took to complete the last frame (Read Only).http://docs.unity3d.com/ScriptReference/Time-deltaTime.html
So basically you have yourself a float variable called Rotate which is lets say 10f
Then inside of your Update function
void Update ()
{
if(Rotate > 0)
{
Rotate -= Time.deltaTime;
ForCube.transform.Rotate (10, 10, 10);
}
}
Then when Rotate is equal to 0 it will stop, but then you can use your work bool to start a new timer.
One big think to take in is to use the Time.deltaTime, if you don't use this and you just use an int or whatever variable type the timer will differ depending on the FPS of the game for the player.
Let me know if you need anymore help :)
Instead of using coroutines, you can do it directly in the update function like this:
[SerializeField]
private float timeToWait; //In seconds
[SerializeField]
private float timeToRotate; //In seconds
private float timer = 0;
private bool waiting = true; //Set this to false if you want to rotate first, wait later
void Update()
{
if(!waiting) RotateYourObjectALittleBit(); //Call your own function or do whatever you want
timer += Time.deltaTime;
if(timer >= timeToWait && waiting) {
waiting = false;
timer = 0;
}
else if(timer >= timeToRotate && !waiting) {
waiting = true;
timer = 0;
}
}
This code is untested, so please let me know if you require further clarification or if it doesn't work.
Thanks everyone for fast Answer and help to solve my problem. I really appreciate that.
I created something like this:
Version 1.0
When the space key is down the cube start rotating for RotateTime, after this the Timer reset to start value(RotationTime), and u can click again button for rotate.
using UnityEngine;
using System.Collections;
public class Ruch : MonoBehaviour
{
public GameObject ForCube;
public float RotateTime = 5;
public float Timer = 0;
private bool Rotate = false;
// Use this for initializat
void Start ()
{
Timer = RotateTime;
ForCube = GameObject.Find ("Cube");
Debug.Log (ForCube);
}
// Update is called once per frame
void Update ()
{
//Start Rotating When Press Space Key
if (Input.GetKeyDown (KeyCode.Space)) Rotate = true;
else if (!(Input.GetKeyDown (KeyCode.Space))&&Timer <=0) Rotate = false;
RotateForSec (ref Timer);
}
//Function to Rotate for X sec
void RotateForSec(ref float sec)
{
if (Rotate && sec > 0) {
Debug.Log (Time.time);
ForCube.transform.Rotate (10, 10, 10);
sec -= Time.deltaTime;
}
//Reset Rotating Time after rotating
if (!Rotate && sec <= 0) Timer = RotateTime;
}
}
Version 2.0
The rotating of cube continues for 5 seconds and then automatically without pressing a key it wait some time and start over rotating. Again again and again ...
public GameObject ForCube;
public float RotateTime = 5;
public float Timer = 0;
public float PauseTime = 0;
private bool Pause = false;
private bool Rotate = true;
// Use this for initializat
void Start ()
{
Timer = RotateTime;
PauseTime = RotateTime;
ForCube = GameObject.Find ("Cube");
Debug.Log (ForCube);
}
// Update is called once per frame
void Update ()
{
//Start Rotating When Press Space Key
if (Rotate)
Pause = false;
else if (!Rotate) {
Pause = true;
}
if (!Pause)
RotateForSec (ref Timer);
else RotatePause ();
}
//Function to pause PauseTime sec
void RotatePause()
{
if (PauseTime > 0) {
PauseTime -= Time.deltaTime;
} else {
Pause = false;
Rotate = true;
PauseTime = RotateTime;
}
}
//Function to Rotate for X sec
void RotateForSec(ref float sec)
{
if (Rotate && sec > 0) {
Debug.Log (Time.time);
ForCube.transform.Rotate (10, 10, 10);
sec -= Time.deltaTime;
} else Rotate = false;
//Reset Rotating Time after rotating
if (!Rotate && sec <= 0) Timer = RotateTime;
}
}
Its working but what you think about that, is it done correctly or it is a bad way?

Categories

Resources