- Home /
How do I increase the speed an instantiated object spawns in with?
Hi everyone, I am trying to make an endless runner game where the player stands stationary on a platform, and objects are instantiated in different patterns further down the platform with an initial speed. I want those objects to increase their speed after a certain time interval is met. For example, if the time interval was 30 seconds and the baseline speed was 10, I would want the speed to go to 20 after 30 seconds have passed, then increase to 30 after another 30 seconds have past, etc. I have a spawner spawning in obstacle patterns with spawn points in various areas.
As of right now, the obstacles spawn in with the same speed no matter what, but increase their speed once they've been spawned in for the duration of the time interval. For example, object 1 is spawned in, moves for 5 seconds at the initial speed, then increases speed, followed by object 2 which does the exact same thing as object 1 upon spawning. Here is my object movement code:
using UnityEngine;
public class ObstacleMovement : MonoBehaviour
{
public Rigidbody rb;
// Keeps track of the time and increases speed based off the time
float time;
int seconds;
public int timeInterval; // Time interval where speed is increased
// Speed stuff
public Vector3 speedInc; // Speed increase each time interval
public float initialSpeed; // Initial speed in the Z direction
Vector3 currentSpeed; // Current speed of the object
// Vars for locking the object in place so no rotation/sliding occurs
float startPositionX;
Quaternion startRotation;
// Start is called before the first frame update
void Start()
{
startPositionX = transform.position.x;
startRotation = transform.rotation;
currentSpeed = new Vector3(0, 0, initialSpeed);
rb.velocity = currentSpeed;
}
// Update is called once per frame
void Update()
{
TrackTime();
if (seconds == timeInterval) {
currentSpeed = SpeedUp(currentSpeed);
time = 0;
}
rb.velocity = currentSpeed;
Debug.Log("Speed is: " + currentSpeed);
LockPos();
}
Vector3 SpeedUp(Vector3 iSpeed) {
Vector3 newSpeed = iSpeed + speedInc;
Debug.Log("Speeding up");
return newSpeed;
}
void TrackTime() {
time += Time.deltaTime;
seconds = (int)time % 60;
Debug.Log(seconds + " seconds have past");
}
void LockPos() {
Vector3 pos = transform.position;
pos.x = startPositionX;
transform.position = pos;
transform.rotation = startRotation;
}
}
In the code above I am creating a timer, keeping track of the seconds, and then increasing the speed after XXX seconds have passed. What am I doing wrong? I can post the code of the spawner and spawn points if that's necessary. Is there a more appropriate place for this to be executed? Thanks!!