- Home /
Rotation Help
I have some code that I want a GameObject and I want it to rotate 4 degrees first and then -4 degrees after the 4 degrees is finished. I have some code which I think should work...
var xrot : float;
var bool : boolean;
var speed : float;
function Start(){
InvokeRepeating("run", 0, 0.01);
var otherscript : Leg_Move_02;
var thisscript : Leg_Move;
}
function run() {
if(bool==true){
xrot -=speed;
}
if(bool==false){
xrot +=speed;
}
if(xrot >4){
bool=true;
}
if(xrot <-4){
bool=false;
}
transform.Rotate(xrot, 0, 0);
}
But for some reason, it gets to 0 and then goes back to 4 and not -4. Why is this happening?
Any Answers Are Appreciated
[EDIT] I decided to put in an example.
1) Create a new scene and add a gameobject in front of the camera
2) Create a cube and place that inside the gameobject
3) Add the script above to the gameobject and change the var speed (in the editor) to 0.25
4)You will see what I mean.
[/EDIT]
So you want it to go between 4 and -4? Essentially a full pendulum?
I want it to go between to values (I've chose 4 because it has been working the best) that cross 0.
Answer by robertbu · Jul 29, 2013 at 03:14 PM
@Kristian has the right idea. transform.Rotate() is a relative rotation. So each time you call it, you are not rotating to the specified degrees, but adding more rotation each frame. If you want it to just rotate from -4 to 4 degrees, you can do this:
#pragma strict
var xrot : float;
var bool : boolean;
var speed : float= 0.1;
var v3Rot = Vector3.zero;
function Start(){
InvokeRepeating("run", 0, 0.01);
var otherscript : Leg_Move_02;
var thisscript : Leg_Move;
}
function run() {
if(bool==true){
xrot -=speed;
}
if(bool==false){
xrot +=speed;
}
if(xrot >4){
bool=true;
}
if(xrot <-4){
bool=false;
}
v3Rot.x = xrot;
transform.eulerAngles = v3Rot;
}
Answer by Kristian · Jul 29, 2013 at 03:04 PM
Well, one problem I see here is that you rotate with xrot every cycle. Meaning that you will rotate speed*0.01 then speed*0.02 then speed*0.03 etc. Resulting in a rotation of approximately 800 degrees ((4/0.01) * (4/2)).
About your other issue, I'm not sure I'm getting the issue, it seems understandable that it should start as 0 and then go to 4, as it first enters the (xrot += speed) line, due to the bool starting as false by default.
I hope this helped in some way :)