- Home /
How do I make an object rotate to rotation given by the keyboard?
I'm trying to create a script where a number typed from the keyboard directly controls an objects rotation. Im doing this so that i can have another software which emulates keystrokes emulate a typing a number on a keyboard and having an object rotate to that number. the code i created is:
transform.rotation.y = (Input.inputString);
the problem is when i run it i get:
Cannot convert 'String' to 'float'. does anyone have a way i can take keyboard inputted numbers and use them to control an objects rotation? thank you.
You need to do a few tutorials before whatever answer you get would make sense to you. Sorry.
Are you trying to do something like this: Type "60" on the keyboard and then the object will rotate 60 degrees?
Answer by aldonaletto · Nov 07, 2013 at 03:32 AM
The whole thing is wrong: you can't assign a string to a float directly, and transform.rotation is a Quaternion, whose xyzw components have nothing to do with those nice angles you see in the Inspector under the caption Rotation - they are actually transform.eulerAngles.
You could use something like this instead:
private var text: String;
function Update(){
for (var c: char in Input.inputString) {
if ("01234567890.-".IndexOf(c) >= 0){ // if numeric key...
text += c; // add it to text
} else { // otherwise finish input:
var angle: float;
// if valid number in text...
if (float.TryParse(text, angle)){ // store it in angle...
// and set eulerAngles.y to the number typed:
transform.eulerAngles = Vector3(0, angle, 0);
}
text = ""; // let text ready for next number
}
}
}
This code concatenates numeric chars (digits, decimal dot or minus sign) in the variable text, and when a non-numeric key (like Enter/Return) is pressed it tries to convert text to a float and rotates the object to this angle.