- Home /
Is anyone able to fix my code?
Alright, I've got this code here:
var speed : float = 5;
var torsoRotation : float = 0;
function Update(){
torsoRotation = transform.Rotate(0, Input.GetAxis("Mouse X") * speed, 0, Space.World);
Mathf.Clamp(torsoRotation, -30, 30);
}
This is the error I get in Unity:
Assets/Scripts/mouseRotate.js(5,35): BCE0022: Cannot convert 'void' to 'float'.
I have a full player model. I was trying to get the torso to rotate slightly left and right, as I moved the mouse those directions in first-person. (Just a little bit of realism.) It worked! I added a variable to store the rotation in, and then I clamped it, so it would not rotate infinitely. Then, it did not work.
Of course, my logic is probably completely wrong. Is anyone able to explain what I did wrong? Am I unable to store the rotation?
Answer by xtvs · Mar 09, 2014 at 09:40 PM
transform.Rotate does not return a value, so assigning it to a float doesn't make any sense. Calculate the value you want to rotate by, clamp it, and then rotate the object.
Try this:
var speed : float = 5;
var torsoRotation : float = 0;
function Update() {
torsoRotation = Input.GetAxis("Mouse X") * speed;
Mathf.Clamp(torsoRotation, -30, 30);
transform.Rotate(0, torsoRotation, 0, Space.World);
}
Answer by noooodley · Mar 09, 2014 at 09:15 PM
You are assuming that the method 'Rotate' returns a float when it actually returns nothing (void). Maybe something like:
function Update() {
transform.Rotate(0, Input.GetAxis("Mouse X") * speed, 0, Space.World);
torsoRotation = transform.eulerAngles.y;
//the rest of your code...
}
Answer by SirCrazyNugget · Mar 09, 2014 at 09:21 PM
transform.Rotate doesn't return a value, it merely calls a function which Rotates around the given axis.
Try something like
function Update(){
torsoRotation = Mathf.Clamp(torsoRotation + Input.GetAxis("Mouse X") * speed * Time.deltaTime, -30, 30);
transform.rotation = Quaternion.Euler(0, torsoRotation, 0);
}
This should, if I've wrote it right, limit the transform Y rotation between -30 and 30 which I think is what you're after.
3 people just gave you the right answer, and now you're going off on a tangent- did you understand the explanation? If so, mark an answer correct.
To do 2 axis rotation, parent the object to two empty transforms and use one only for y pivot and one only for x tilt. It will make things easier than trying to rotate the same transform on two axes at once.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
What is wrong with this script? 2 Answers
Sprite facing object to mouse 0 Answers
How do I clamp my rotation? 4 Answers
An object reference is required for the non-static field, method, or property 1 Answer