- Home /
Question by
TaskiPoike · Oct 23, 2021 at 01:12 PM ·
movementmovement scriptmove an objectmovementsinstantly
How can i make it so that the object doesnt instantly go to top speed. Here is my code
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class liikkuu : MonoBehaviour { Rigidbody m_Rigidbody; float m_Speed;
void Start()
{
//Fetch the Rigidbody component you attach from your GameObject
m_Rigidbody = GetComponent<Rigidbody>();
//Set the speed of the GameObject
m_Speed = 30.0f;
}
void Update()
{
if (Input.GetKey(KeyCode.W))
{
//Move the Rigidbody forwards constantly at speed you define (the blue arrow axis in Scene view)
m_Rigidbody.velocity = transform.forward * m_Speed;
}
if (Input.GetKey(KeyCode.D))
{
transform.Rotate(0, 1f, 0);
}
if (Input.GetKey(KeyCode.A))
{
transform.Rotate(0, -1f, 0);
}
}
}
Comment
Best Answer
Answer by ChaosEaterY · Oct 23, 2021 at 01:39 PM
The problem is with this line:
m_Rigidbody.velocity = transform.forward * m_Speed;
if you want to gradually accelerate to top speed, you should do something like this:
public float MinSpeed = your minimum speed ;
public float MaxSpeed = m_Speed;
public float accelerationSpeed;
float CurrentSpeed;
void Update()
{
if (Input.GetKeyDown(KeyCode.W)) // on key W down set current speed to minimum speed
{
CurrentSpeed = MinSpeed;
}
if (Input.GetKey(KeyCode.W)) // accelerate while holding the key
{
CurrentSpeed += accelerationSpeed;
m_Rigidbody.velocity = transform.forward * CurrentSpeed ;
}
if (Input.GetKeyUp(KeyCode.W)) // on key W up reset current speed to minimum speed
{
CurrentSpeed = MinSpeed;
}
}