how to move an object to a lacation slowly?

I am making a FPS, when i press E, the character leans and the camera rotates a bit and moves to the right here’s how it looks

if(Input.GetKey(KeyCode.E))
{
transform.localRotation = Quaternion.Euler(xRotation, 0f, -15f);
transform.localPosition = new Vector3 (0.25f, 1.625f, 0f);
}

when i do this, it just moves to the right and rotate instantly, i want a slow and natural movement, so i tried another way

if(Input.GetKey(KeyCode.E))
{
transform.Translate(0.25f, 1.625f, 0f);
}

when i do this, the camera moves to the right until i release the key

anyone knows how i can make it rotate and translate slowly without animations or too complicated code?

Hey @GabrielTheSnake,

Check out Catlike Coding’s tutorials on character movement in Unity – they are absolutely brilliant.


You’re on the right track with your code that’s calling transform.Translate. In order to move faster or slower, you will want to give your character some sort of time-dependent “speed” field that you can adjust from the inspector. Here’s is a pretty short and simple player movement script that might give you some inspiration:

using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    public float moveDistancePerSecond = 10.0f;     // Move speed
    public float rotationDegreesPerSecond = 360.0f; // Rotation speed

    void Update()
    {
        var secondsSinceLastUpdate = Time.deltaTime;

        // Get player movement input
        var desiredMovement = Vector3.zero;
        var moveDistance = moveDistancePerSecond * secondsSinceLastUpdate;
        if (Input.GetKey(KeyCode.W)) { desiredMovement.z += moveDistance; }
        if (Input.GetKey(KeyCode.A)) { desiredMovement.x -= moveDistance; }
        if (Input.GetKey(KeyCode.S)) { desiredMovement.z -= moveDistance; }
        if (Input.GetKey(KeyCode.D)) { desiredMovement.x += moveDistance; }

        // Get player rotation input
        var desiredRotation = 0f;
        var rotationAmount = rotationDegreesPerSecond * secondsSinceLastUpdate;
        if (Input.GetKey(KeyCode.E)) { desiredRotation += rotationAmount; }
        if (Input.GetKey(KeyCode.Q)) { desiredRotation -= rotationAmount; }

        // Execute the desired the movement and rotation from above
        transform.Translate(desiredMovement);
        transform.Rotate(0, desiredRotation, 0);
    }
}

This doesn’t handle physics of any kind, but is an ok place to start experimenting with moving things around via code.

I would also suggest looking into Unity’s built-in CharacterController component to help you move your player. It is fairly popular, so there are several tutorials on the internet to help you learn how to use it.