Hey, I’m making a 2d game and my character is a sphere. How can I make so that it takes like .5 seconds of holding A or D to make my character get to top speed? Right now it goes top speed the instant I press A or D. Also how can I make the character keep on moving the direction its going even if A or D is let go? Could I get some sample code? Thanks.
There could be several ways, depending on how your character is set up.
If you have a Rigidbody
component attached to the character GameObject
, you could use
public var speed : float = 5;
function Update()
{
rigidbody.AddForce(Vector3(
Input.GetAxis("Horizontal") * speed,
Input.GetAxis("Vertical") * speed,
0));
}
Read more about Rigidbody.AddForce()
here.
You could also have a velocity vector which is updated as a key is pressed, like in this simple example (JavaScript):
public var friction : float = 0.2;
public var speed : float = 0.1;
private var velocity = Vector3(0, 0, 0);
function Update()
{
velocity.x += Input.GetAxis("Horizontal") * speed;
velocity.y += Input.GetAxis("Vertical") * speed;
transform.position += velocity;
velocity *= friction;
}
They both do basically the same thing, except one uses the built-in physics engine, and the other uses your own.
As for keeping the character moving in a direction for a longer time, you can increase the speed
variable or decrease the Rigidbody
’s mass in the Rigidbody
example, and reduce the friction
or speed
variable in the second example.
I hope this answers your question!
Additional code (see comments below):
public var collisionParticles : ParticleEmitter;
public var wall : Collider;
function OnTriggerEnter(Collider other)
{
if (other == wall)
{
// instantiate a particle system in the current location with no rotation
Instantiate(collisionParticles, transform.position, Quaternion.identity);
// destroy this GameObject
Destroy(gameObject);
}
}
@script RequireComponent(Rigidbody)
There is a window where you can change the arrow keys “speed up” and “coast” rates. Select Edit->ProjectSettings->Input. The Inspector will change. Pop open Axes and then Vertical.
Sesitivity is how fast it speeds up, and gravity is coast speed.
Setting Sensitve/Grav to 0.2 will give 5 secs of holding UP arrow to reach full speed, and 5 secs to coast to 0. The range of “Vertical” is from -1 (backwards) to 1 (forwards.) So, the current value of 3 means it adds 3/second, getting to full speed in 1/3 of a second.
I’ve never tried it, but a Gravity of 0 (or really small) should make it coast forever.
Any script which uses Input.GetAxis(“Vertical”) uses these settings. Snap is also fun to look at, while the menu is open (it makes you have to slow down before changing directions.)