x


pressing button enables motor forever?

so im using an extremely simple script to rotate a motor forwards and backwards. and it works like charm for doing just that. however i would like it to only rotate when the button is held down, and free spin when nothing is pressed. as of right now you press up once and it rotates forever at the force thats set. here is the script im using at the moment. ive also tried using GetKeyDown and that didnt work either. i am very new to unity and scripting all together, any help is greatly appreciated

    function FixedUpdate () {
if (Input.GetKey ("up"))
    hingeJoint.motor.force = -10;
    hingeJoint.motor.targetVelocity = -10;
    hingeJoint.motor.freeSpin = true;
if (Input.GetKey ("down"))
    hingeJoint.motor.force = 10;
    hingeJoint.motor.targetVelocity = 10;
    hingeJoint.motor.freeSpin = true;

}

more ▼

asked Oct 10 '10 at 11:18 PM

Hondune gravatar image

Hondune
15 3 3 5

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

2 answers: sort voted first

If you haven't already figured it out, I think this else statement should do the job.

You might also want to remove the .freespin = true; if you never set it to anything else

if (Input.GetKeyDown("up"))
{
    hingeJoint.motor.force = -10;
    hingeJoint.motor.targetVelocity = -10;
    hingeJoint.motor.freeSpin = true;
}
else if (Input.GetKeyDown("down"))
{
    hingeJoint.motor.force = 10;
    hingeJoint.motor.targetVelocity = 10;
    hingeJoint.motor.freeSpin = true;
}
else
{
    hingeJoint.motor.force = 0;
    hingeJoint.motor.targetVelocity = 0;
    hingeJoint.motor.freeSpin = true;
}
more ▼

answered Nov 02 '10 at 04:32 AM

Atnas1010 gravatar image

Atnas1010
1.1k 6 10 26

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

You need to add braces, otherwise the if statement will only conditionally affect the one line after it.

if (Input.GetKeyDown("up"))
{
    hingeJoint.motor.force = -10;
    hingeJoint.motor.targetVelocity = -10;
    hingeJoint.motor.freeSpin = true;
}
if (Input.GetKeyDown("down"))
{
    hingeJoint.motor.force = 10;
    hingeJoint.motor.targetVelocity = 10;
    hingeJoint.motor.freeSpin = true;
}
more ▼

answered Oct 10 '10 at 11:26 PM

Marowi gravatar image

Marowi
4.9k 4 14 53

ah, yes thank you for that! i was wondering why changing velocity didnt do anything. works much better now. still having the original problem though unfortunately :/

Oct 11 '10 at 03:21 AM Hondune
(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:

x786
x724
x146
x40
x25

asked: Oct 10 '10 at 11:18 PM

Seen: 869 times

Last Updated: Oct 10 '10 at 11:18 PM