- Home /
Sometimes "GetKey" does not work. why?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Force : MonoBehaviour {
private Rigidbody rb;
int i = 0;
public int limit_max = 1000;
public int limit_min = 50;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody>();
enabled = false;
}
// Update is called once per frame
void Update () {
Vector3 temp = rb.velocity;
float mag = temp.sqrMagnitude;
if (Input.GetKey("a") && mag<limit_max || mag<limit_min)
{
rb.velocity *= 1.1f;
Debug.Log(i + " Accel");
}
if (Input.GetKey("s") && mag>limit_min || mag>limit_max)
{
rb.velocity *= 0.9f;
Debug.Log(i + " slow");
}
Debug.Log(i + " : " + mag);
i++;
}
}
Sometimes "GetKey" works, Sometimes is not. I don't know Why...
You set enabled = false; in the Start. When do you enable it again? Your Update will only run with the script enabled.
Answer by Vega4Life · Dec 03, 2018 at 12:40 AM
The problem isn't the GetKey, it's the velocity of the object. Once the object gets to zero velocity, it wont ever move again.
This is because you have a zero velocity object, and you multiply it by some acceleration or declaration number. Anything multiplied by zero, is zero.
rb.velocity *= 1.1f; // This won't move the object when it has zero velocity!! This is zero!
Once magnitude hits zero, it will act like it doesn't work anymore.
You are right about the acceleration wouldn't work if the velocity is 0. However if the velocity once is greater than 0 it can never reach 0 due to the || mag<limit_$$anonymous$$
which will force accelerate even without pressing "a" so velocity always stays above roughly "7" (==sqrt(50)). Likewise if the velocity goes over about 31.6 it will force a slow down. We don't ´know if the object has some initial velocity or not and if it's possible for the velocity to completely stop (due to collision). There are many things not clear. The enabled = false thing Ivovd$$anonymous$$arel mentioned in the comment may also play a role. The script might be enabled from the outside, though we just don't know.
Your answer
