I saw this question asked here: How do you fix a Rigidbody stopping quickly after the addforce stops being called? - Questions & Answers - Unity Discussions
but wasn’t answered sufficiently.
I have a spaceship GameObject and all I’m doing is this:
if (Input.GetKey (KeyCode.Space)) {
rb.AddForce (transform.forward * 100, ForceMode.Impulse);
}
And as soon as I let go of the key, the ship stops moving. What I’m wanting is for the boost to decay (like it’s supposed to).
When I use GetKeyDown(), which is closer to what I’m going for, it just jumps forward for a split second.
The ship is supposed to be moving forward constantly, and I’ve tried this both by modifying the position directly and by keeping a constant velocity on the RigidBody, but I get the same result.
There is no drag on the RigidBody. I’ve tried it without all the other movement and RigidBody code. I’ve tried it in both Update() and FixedUpdate(). I’ve tried all the other ForceModes. The GameObject has no other scripts attached.
public class PlayerController : MonoBehaviour {
public float tilt;
public Boundary moveBoundary;
public float forwardSpeed;
public int pickups = 0;
public int missedPickups = 0;
public int enemies = 0;
public int missedEnemies = 0;
private Rigidbody rb;
private GameController gameController;
private Shooter shooter;
void Awake ()
{
GameObject gameControllerObject = GameObject.FindWithTag("GameController");
if (gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent<GameController>();
}
if (gameController == null)
{
Debug.Log("Cannot find 'GameController' script");
}
rb = GetComponent<Rigidbody> ();
shooter = GetComponent<Shooter> ();
}
void Start ()
{
}
void Update ()
{
if (Input.GetButton ("Fire1") /*&& gameController.CanShoot()*/) {
shooter.Shoot ();
//gameController.AddShot ();
}
transform.position += transform.forward*forwardSpeed*Time.deltaTime;
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 targetRotation = new Vector3 (-1 * moveVertical, moveHorizontal, -1 * moveHorizontal) * 20;
transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.Euler (targetRotation), Time.fixedDeltaTime * tilt);
transform.position = new Vector3 (
Mathf.Clamp (rb.position.x, moveBoundary.xMin, moveBoundary.xMax),
Mathf.Clamp (rb.position.y, moveBoundary.yMin, moveBoundary.yMax),
rb.position.z
);
}
void FixedUpdate()
{
if (Input.GetKey (KeyCode.Space)) {
rb.AddForce (transform.forward * 50, ForceMode.Impulse);
}
//rb.velocity = transform.forward * forwardSpeed;
}
void OnTriggerEnter (Collider other) {
if (other.gameObject.CompareTag ("Pickup")) {
pickups += 1;
Destroy (other.gameObject);
}
}
}