- Home /
Rotation strange
Hi, I have a character that can turn left or right, based on the the button that you press. But there is a problem, sometimes the character stops to turn and sometimes goes faster, sometimes goes slower.... I don't know why this happened... This is my code:
float ang,y;
Vector3 moveDirection,angle2,move;
void Update () {
moveDirection = this.transform.position;
angle = this.transform.rotation;
angle.y = angle.y % (2 * Mathf.PI);
anim.SetBool ("IsWalking", false);
if (Input.GetKey (KeyCode.RightArrow)) {
this.transform.Rotate (0, angle.y + 1f, 0);
} else if (Input.GetKey (KeyCode.LeftArrow)) {
this.transform.Rotate (0, angle.y - 1f, 0);
}
if (Input.GetKey (KeyCode.UpArrow)) {
float a = 0.04f;
angle2 = transform.eulerAngles;
ang = (Mathf.Abs (Mathf.Deg2Rad * angle2.y)) % (2 * Mathf.PI);
moveDirection.x += a * Mathf.Sin (ang);
moveDirection.z += a * Mathf.Cos (ang);
}
this.transform.position = moveDirection;
}
Help me please :D :D
Answer by robertbu · Mar 22, 2014 at 02:49 PM
Your rotate has a couple of problems. Transform.Rotate() incrementally changes the rotation. It is a relative rotation. You are trying to use it as an absolute rotation. In addition you are not scaling by Time.deltaTime. Try this this instead:
transform.Rotate(0,rotationSpeed * Time.deltaTime, 0);
'rotationSpeed' would be declared at the top of the file and be degrees per second.
You are also not scaling your movements by Time.deltaTime. The amount of time that passes each frame varies. When there is a heavier load, then the fps drops and deltaTime increases. And your movement code is going the long way around. Try this:
if (Input.GetKey (KeyCode.UpArrow)) {
transform.position = transform.forward * speed * Time.deltaTime;
}
Alternate that does the same thing:
if (Input.GetKey (KeyCode.UpArrow)) {
transform.Translate(0,0,speed * Time.deltaTime);
}
'speed' will be a variable you define at the top of the file and will be set to the units per second you want to move.
I tried but it doesn't work, can you change my code please ? :)
Here is the essence of my suggestion as a complete script. Start with a new scene, add a cube, add this script. Use the arrow keys to rotate and move. Once you've verified that the logic works, you can integrate the changes back into your code.
using UnityEngine;
using System.Collections;
public class Bug25b : $$anonymous$$onoBehaviour {
float rotationSpeed = 135.0f; // Degrees per second;
float speed = 3.0f; // Units per second
void Update () {
if (Input.Get$$anonymous$$ey ($$anonymous$$eyCode.RightArrow)) {
transform.Rotate(0,rotationSpeed * Time.deltaTime, 0);
} else if (Input.Get$$anonymous$$ey ($$anonymous$$eyCode.LeftArrow)) {
transform.Rotate(0,-rotationSpeed * Time.deltaTime, 0);
}
if (Input.Get$$anonymous$$ey ($$anonymous$$eyCode.UpArrow)) {
transform.Translate(0,0,speed * Time.deltaTime);
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613140900im_/https://answers.unity.com/themes/thub/images/avi.jpg)