Hi, I was wondering if anyone could help me here. I have been making a script to make a game object (in this case, a mini-gun barrel)rotate when the primary mouse button is pressed, but I also want it to accelerate for a second or so before getting to the full rotation speed. For starters, I don’t actually know how to do the acceleration part, but the biggest problem I’ve had, is that the firing sequence acts immediately. So there’s the second problem.
At the moment my script is:
var speed;
transform.rotation(0,0,7)
so how would I fix this up to make the acceleration work?
Havn’t tested this, but something along these lines should do the trick.
You’ll probably want to fiddle around with the MaxSpinRate. A modern minigun would rotate at a rate in the vicinity of the framerate and who knows what that would look like. Want to keep it fairly low.
Because of the way the spinup timer is implemented, if the gun starts firing again before its spun all the way back down, it will be a shorter trip to the “fast enough to fire” point.
bool Firing;
float SpinUpTime = 2; // two seconds to spin up
float SpinUpTimer;
float MaxSpinRate = 360; // degrees per second
void Update()
{
Firing = Input.GetButton("Fire1");
if (Firing)
{
SpinUpTimer = Mathf.Clamp(
SpinUpTimer + Time.deltaTime,
0, SpinUpTime);
if (SpinUpTimer >= SpinUpTime)
{
// Emit bullets here
}
}
else
{
// Not firing now. Spin back down
SpinUpTimer = Mathf.Clamp(
SpinUpTimer - Time.deltaTime,
0, SpinUpTime);
}
// Spin the barrels
float theta = (SpinUpTimer / SpinUpTime) *
MaxSpinRate * Time.deltaTime;
transform.RotateAroundLocal(
Vector3.forward, theta);
}
So far, it worked perfectly… I take it that I put the script for firing in the part where it says “emit bullets here”? The rotation rate at degrees per second is new to me though. But thanks.
Happy to oblige.
Most coefficients that define movement should be in a units/time rate and then integrated with Time.deltaTime when you use them. Otherwise you are doing things in units/frame. Which is fine as long as frames run at a consistant rate. But you can’t count on that.
For a cosmetic movement like this one, doesn’t matter. If you were moving or firing bullets over time, it would - framerate drop would change your rate of fire and bullet speed.
Sweet, that helped heaps. You’re definitely going to be in the credits for this game. This was the hardest part so far (there is lots to go.)