- Home /
How to change boolean state based on User Input?
Hello all,
Below is a screenshot of my character movement code. It's missing one element; I need to change the boolean "xMove" based on users input.
I tried the if statement on line 19 but got the following error: "Cannot implicitly convert type float' to
bool'"
So how would I go about correcting this issue?
using UnityEngine;
using System.Collections;
public class SteveMovement : MonoBehaviour
{
//Set Player Movement Speed
public float speed = 10.0f;
//Boolean to check if Horizontal movement keys are down
void Start () {
//Set Starting Location
transform.position = new Vector3(5, 0, 0);
}
void Update () {
//Move Character left and right
//If xMove == true --type bool
//Move along Horizontal axis * speed * hardwareSpeed
if (Input.GetAxis("Horizontal") > 0.5f){
Debug.Log("Horizontal Button Is Down");
//Execute movement along Horizontal Axis
transform.Translate(Input.GetAxis("Horizontal") * Vector3.forward * speed * Time.deltaTime);
//Insert animation clip via Animator
animation.Play("Walk");
}else{
Debug.Log("Player is not pressing Horizontal movement button");
animation.Play(); //Deafault animation is "Idle"
}
//Old Movement method
//transform.Translate(Vector3.right * Input.GetAxis("Horizontal") * speed * Time.deltaTime); //Move gameObject on the X axis
//Debug.Log("Old Horizontal Movement Initiated");
}
}
Thanks in advance for all help offered. :)
-Joshua4missions
Answer by Ejlersen · Aug 07, 2013 at 05:27 PM
if (Input.GetButton("Horizontal"))
{
transform.Translate(Vector3.right * speed * Input.GetAxis("Horizontal") * Time.deltaTime);
if (!xMove)
{
animation.Play("Walk");
xMove = true;
}
}
else
{
if (xMove)
{
animation.Play();
xMove = false;
}
}
Okay, the project started so no compile errors that prevented it.
New development is that I can only move right, not left. No animations play as well. I guess I need to make a new topic concerning how to connect an Animator setup to code so that this doesn't go off topic. :/
Code is in OP. I edited the Vector3.right to Vector3.forward to fix a directional problem that developed.