Reputation: 23
using UnityEngine;
using System.Collections;
public class RightMovement : MonoBehaviour {
public float maxSpeed = 10f;
bool facingRight = true;
void Start() {}
void FixedUpdate() {
float move = (Input.GetAxis("Horizontal") > 0);
rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);
}
}
This is the full error I keep getting:
Assets/Scripts/RightMovement.cs(14,23): error CS0029: Cannot implicitly convert type
bool' to
float'
I want to use Input.GetAxis("Horizontal")
to move my sprite character, but I only want him to move right.
Upvotes: 1
Views: 7305
Reputation: 881353
Input.GetAxis("Horizontal") > 0
is a Boolean (true/false) value which will be true if the return value from GetAxis
is greater than zero, or false otherwise. That's why it's complaining about trying to shoehorn a Boolean into a float variable.
It sounds like you want to force it to be non-negative only, in which case there are two likely possibilities.
The first is to ensure that negative values are translated to zero and that would involve something like:
float move = Input.GetAxis("Horizontal");
if (move < 0) move = 0;
or, if you're the sort that prefers one-liners:
float move = Math.Max(0, Input.GetAxis("Horizontal"));
The second would be to translate negative to the equivalent positive, something like:
float move = Input.GetAxis("Horizontal");
if (move < 0) move = -move;
or, again, a one-liner:
float move = Math.Abs(Input.GetAxis("Horizontal"));
I suspect the former is probably what you're after but you should think about what you want negative values turned in to, and adjust to that.
Upvotes: 2