Bastein
Bastein

Reputation: 11

Player only moving forward for one tick

I found this piece of code online

// Do not apply input if we are showing a level selection display
if(HaltUpdateMovement == true)
    return;

bool moveForward = false;
bool moveLeft    = false;
bool moveRight   = false;
bool moveBack    = false;

MoveScale = 1.0f;

// * * * * * * * * * * *
// Keyboard input

// Move

// WASD
if (Input.GetKeyDown(KeyCode.W)) moveForward = true;
if (Input.GetKey(KeyCode.A)) moveLeft    = true;
if (Input.GetKey(KeyCode.S)) moveBack    = true; 
if (Input.GetKey(KeyCode.D)) moveRight   = true; 
// Arrow keys
if (Input.GetKeyDown(KeyCode.UpArrow))    moveForward = true;
if (Input.GetKey(KeyCode.LeftArrow))  moveLeft    = true;
if (Input.GetKey(KeyCode.DownArrow))  moveBack    = true; 
if (Input.GetKey(KeyCode.RightArrow)) moveRight   = true; 

if ( (moveForward && moveLeft) || (moveForward && moveRight) ||
     (moveBack && moveLeft)    || (moveBack && moveRight) )
    MoveScale = 0.70710678f;

// No positional movement if we are in the air
if (!Controller.isGrounded) 
    MoveScale = 0.0f;

MoveScale *= DeltaTime;

// Compute this for key movement
float moveInfluence = Acceleration * 0.1f * MoveScale * MoveScaleMultiplier;

// Run!
if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
    moveInfluence *= 2.0f;

if(DirXform != null)
{
    if (moveForward)
        MoveThrottle += DirXform.TransformDirection(Vector3.forward * moveInfluence);
    if (moveBack)
        MoveThrottle += DirXform.TransformDirection(Vector3.back * moveInfluence) * BackAndSideDampen;
    if (moveLeft)
        MoveThrottle += DirXform.TransformDirection(Vector3.left * moveInfluence) * BackAndSideDampen;
    if (moveRight)
        MoveThrottle += DirXform.TransformDirection(Vector3.right * moveInfluence) * BackAndSideDampen;
}

My problem is, I want my person to move forward without stop once I press w, but he only moves forward for a tick and then stops again, any ideas/help?

Upvotes: 1

Views: 799

Answers (2)

Tim S.
Tim S.

Reputation: 56536

Where is moveForward set to false? It appears to be happening when it shouldn't. Or it's scoped wrong. Is it a local variable (i.e. declared within a method) or a field on the class (i.e. declared directly in the class)? The latter is probably what you're looking for.

bool moveForward = false;

void Update() // or whatever method you had your code in
{
    bool moveLeft  = false;
    bool moveRight = false;
    bool moveBack  = false;
    // do stuff
}

Upvotes: 0

Taylor Brandstetter
Taylor Brandstetter

Reputation: 3623

Use GetKey instead of GetKeyDown. GetKeyDown only returns true during the frame when the user pressed the key, whereas GetKey will continue to return true as long as the key is held.

See: http://docs.unity3d.com/Documentation/ScriptReference/Input.GetKey.html

And: http://docs.unity3d.com/Documentation/ScriptReference/Input.GetKeyDown.html

Upvotes: 3

Related Questions