BelgianWizard
BelgianWizard

Reputation: 109

Unity key input control statement incorrect

This the script I use for the movement of my Endless Runner game made in Unity3D 5.1.2f1 Personal. Moving to the right works completely. Moving the left doesn't work, but the debug.log does work. In the inspector I can see the 'leftrightSpeed' is set to 2 when moving to the right but nothing happens to the float when moving to the left. What am I doing wrong here?

(Float speed is set to 5 in the inspector).

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    public float speed;
    public float leftrightSpeed;
    private Rigidbody rb;

    void Start()
    {
    rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        //LEFT
        if (Input.GetKey("left"))
        {
            leftrightSpeed = -2f;
            Debug.Log ("LEFT");
        }
        else
        {
            leftrightSpeed = 0f;
        }

         //RIGHT
        if (Input.GetKey("right"))
        {
            leftrightSpeed = 2f;
            Debug.Log ("RIGHT");
        }
        else
        {
            leftrightSpeed = 0f;
        }

    Vector3 movement = new Vector3 (-2f, 0.0f, leftrightSpeed);

    rb.AddForce (movement * speed);
    }
}

Upvotes: 0

Views: 98

Answers (2)

Jerry Switalski
Jerry Switalski

Reputation: 2720

You are setting leftrightSpeed to 0 in else block of second condition when you press anything else then right key. That is why it works for right. That is it.

To do it right, change it to

if (Input.GetKey("right"))
    {
        leftrightSpeed = 2f;
        Debug.Log ("RIGHT");
    }
    else if (Input.GetKey("left"))
    {
        leftrightSpeed = -2f;
        Debug.Log ("LEFT");
    }       
    else
    {
        leftrightSpeed = 0f;
    }

Upvotes: 0

LukeP
LukeP

Reputation: 1605

Jerry is correct it is your 2nd if statment that cancels out your Left movement. You could improve your FixedUpdate method by simply using GetAxis like so:

void FixedUpdate()
{
    leftrightSpeed = Input.GetAxis("Horizontal") * 2;
    Vector3 movement = new Vector3 (-2f, 0.0f, leftrightSpeed);
    rb.AddForce (movement * speed);
}

Essentially GetAxis will give a number between -1 and 1 depending on which key is being pressed in correlation to the "horizonal" axis. This will work for game controllers, arrow keys, or even the w/a/s/d movement by default.

Check out the documentation for GetAxis.

Upvotes: 1

Related Questions