Reputation: 9
I am currently developing a 2d game in Unity, it is an endless level runner game. I am trying to increase the speed of the moving objects over time, however the speed keeps reverting. I have tried numerous different ways of changing this code but I cannot seem to get it to work. Does anyone have any ideas?
Here is my code:
public class pipeMove : MonoBehaviour
{
public float speed = 6f;
float targetSpeed = 12f;
void FixedUpdate()
{
transform.position += Vector3.left * speed * Time.deltaTime;
Debug.Log("Speed: " + speed);
if (speed < targetSpeed)
{
speed += 2f * Time.deltaTime;
}
}
}
This is what I'm seeing in my log:
Speed: 7.599998
UnityEngine.Debug:Log (object)
pipeMove:FixedUpdate () (at Assets/scripts/pipeMove.cs:13)
Speed: 12.00009
UnityEngine.Debug:Log (object)
pipeMove:FixedUpdate () (at Assets/scripts/pipeMove.cs:13)
Speed: 12.00009
UnityEngine.Debug:Log (object)
pipeMove:FixedUpdate () (at Assets/scripts/pipeMove.cs:13)
Speed: 11.62008
UnityEngine.Debug:Log (object)
pipeMove:FixedUpdate () (at Assets/scripts/pipeMove.cs:13)
Speed: 9.620035
UnityEngine.Debug:Log (object)
pipeMove:FixedUpdate () (at Assets/scripts/pipeMove.cs:13)
Speed: 7.619998
UnityEngine.Debug:Log (object)
pipeMove:FixedUpdate () (at Assets/scripts/pipeMove.cs:13)
Speed: 12.00009
UnityEngine.Debug:Log (object)
pipeMove:FixedUpdate () (at Assets/scripts/pipeMove.cs:13)
I am not sure what is making the speed increase and decrease rather than just increase.
Upvotes: 0
Views: 1503
Reputation: 1
maybe try to make it a local Variable just so nothing can edit it outside the FixedUpdate.
public class pipeMove : MonoBehaviour
{
void FixedUpdate()
{
float speed = 6f;
float targetSpeed = 12f;
transform.position += Vector3.left * speed * Time.deltaTime;
Debug.Log("Speed: " + speed);
if (speed < targetSpeed)
{
speed += 2f * Time.deltaTime;
}
}
}
Upvotes: 0
Reputation: 103
try this one
using UnityEngine;
public class pipeMove : MonoBehaviour
{
private float speed = 6f;
private float targetSpeed = 12f;
void Update ()
{
if (speed < targetSpeed)
speed += 2f * Time.deltaTime;
}
}
From Unity answers
Upvotes: 1