- Home /
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;
}
Answer by Atnas1010 · Nov 02, 2010 at 04:32 AM
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;
}
Answer by · Oct 10, 2010 at 11:26 PM
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;
}
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 :/