x


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).

more ▼

asked Mar 28 '10 at 09:26 PM

RCIX gravatar image

RCIX
108 4 4 10

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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);
}
more ▼

answered Mar 28 '10 at 10:23 PM

Eric5h5 gravatar image

Eric5h5
81.5k 42 133 529

+1 100% right :) I'll just delete my answer..

Mar 28 '10 at 10:33 PM Lipis

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!

Mar 28 '10 at 10:35 PM RCIX
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5270
x1420
x1070

asked: Mar 28 '10 at 09:26 PM

Seen: 2570 times

Last Updated: Mar 28 '10 at 09:26 PM