Here’s my script, it spins/turns the character left (q
) or right (e
) but it spins too fast. I need it to slowly spin/turn. How do I add a control?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class QE : MonoBehaviour
{
float speed = -25f;
// Start is called before the first frame update
void Start()
{
speed = -25f;
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Q)) {
transform.Rotate(0, -1, 0);
}
if (Input.GetKey(KeyCode.E))
{
transform.Rotate(0, 1, 0);
}
}
}
Hi, KylonZarr
This code should work First I made your speed variable public so you can see and set it on the editor (try to change values of the speed
variable for example to a 100
).Also I you did not need to set it’s value no Start as you have already defined a value while defining it. Also I multiplied your speed with Time.deltaTime
to make your turn smooth.
Note: The code could be optimized but I think it will be enough now. Fell free to ask fi you are confused about something or have any other questions.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class QE : MonoBehaviour
{
public float speed = -25f;
void Update()
{
if (Input.GetKey(KeyCode.Q))
{
transform.Rotate(0, -speed * Tİme.deltaTime, 0);
}
if (Input.GetKey(KeyCode.E))
{
transform.Rotate(0, speed * Tİme.deltaTime, 0);
}
}
}
To control the rotation speed when pressing ‘Q’ and ‘E’ keys, you can introduce a rotation speed multiplier and use Time.deltaTime
to make the rotation frame-rate independent. This way, the rotation speed will be consistent across different frame rates.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class QE : MonoBehaviour
{
public float rotationSpeed = 50f; // Adjust this value to control the rotation speed.
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Q))
{
// Rotate left with the specified speed and frame-rate independence.
transform.Rotate(Vector3.up * -rotationSpeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.E))
{
// Rotate right with the specified speed and frame-rate independence.
transform.Rotate(Vector3.up * rotationSpeed * Time.deltaTime);
}
}
}