- Home /
Movement Script troubles
I wrote the following script:
using UnityEngine; using System.Collections;
public class NewBehaviourScript : MonoBehaviour { // Use this for initialization void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKey("W"))
{
rigidbody.AddForce(new Vector3(0,100), ForceMode.Force);
}
if (Input.GetKey("A"))
{
rigidbody.AddForce(new Vector3(100,0), ForceMode.Force);
}
if (Input.GetKey("S"))
{
rigidbody.AddForce(new Vector3(0,-100), ForceMode.Force);
}
if (Input.GetKey("D"))
{
rigidbody.AddForce(new Vector3(-100,0), ForceMode.Force);
}
}
}
As you can see, a basic script which ought to move the object i dropped it on when i press the WASD keys. However, putting it on my object, it doesnt work. Am i doing anything obviously wrong or anything?
My object is a combo plane/BoxCollider with the plane rotated 90 degrees (to face my camera, the Z axis points down now), and it is constrained to 2 dimensions (X and Y).
Answer by Eric5h5 · Mar 28, 2010 at 10:23 PM
The main problem is that there are no keys called "W", "S" etc.; you should get an error message if you try to use those. The actual names are lowercase ("w", "s", etc.) But instead of hard-coding input (people don't necessarily have QWERTY keyboards), use Input.GetAxis. Also it's better not to hard-code the force since you might need to change that. Using Update without Time.deltaTime will make your code framerate-dependent, but physics should be in FixedUpdate anyway.
public float force = 100;
void FixedUpdate () { rigidbody.AddForce(Input.GetAxis("Horizontal") Vector3.right force); rigidbody.AddForce(Input.GetAxis("Vertical") Vector3.up force); }
You both provide nice answers but i think this one fits better as it both fixes my problem and points out how i could do things better! thanks!