Can't find a way to make object rotate and move at the same time.

Hi,
I’m fairly new to Unity and I’m having some troubles with my first project. Basically, I have a block that slides in the z axis whenever I press the Left/Right arrows or A/D keys. I also want to be able to rotate it by it’s x axis by pressing either the Q/E keys.

The only problem I’m facing is that it either moves or rotates, and I want it to be able to do both at the same time.

Here’s a quick video of the project:

And here’s my object’s movement script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BlockMovement : MonoBehaviour {

    public GameObject cube;


    public float speed;
    public float rotationSpeed;

    public float minRotation = -45f;
    public float maxRotation = 45f;

	void Update () {
        Vector3 moveTo = new Vector3(0f, 0f, Input.GetAxis("Horizontal") * speed * Time.deltaTime);
        cube.GetComponent<Rigidbody>().MovePosition(cube.GetComponent<Transform>().position + moveTo);

        if (Input.GetKey(KeyCode.Q)) {
            cube.GetComponent<Transform>().Rotate(Vector3.right * rotationSpeed * Time.deltaTime);
        } else if (Input.GetKey(KeyCode.E)) {
            cube.GetComponent<Transform>().Rotate(-Vector3.right * rotationSpeed * Time.deltaTime);
        }
	}
}

Note that you don’t need to get the Transform of a gameobject since every gameobject has a transform component by default.


Since your cube has a kinematic Rigidbody you also don’t need to move it with the Rigidbody Component. You can simply use the normal Transform.

using UnityEngine;

public class BlockMovement : MonoBehaviour
{
    public GameObject cube;
    public float speed = 50f;
    public float rotationSpeed = 50f;
    public float minRotation = -45f;
    public float maxRotation = 45f;

    void Update()
    {
        float deltaTime = Time.deltaTime;

        float horizontalInput = Input.GetAxis("Horizontal");
        if (horizontalInput != 0f)
        {
            float deltaMovement = horizontalInput * speed * deltaTime;
            cube.transform.Translate(new Vector3(0f, 0f, deltaMovement));
        }

        bool isTurningLeft = Input.GetKey(KeyCode.Q);
        bool isTurningRight = Input.GetKey(KeyCode.E);
        if (isTurningLeft && !isTurningRight)
        {
            cube.transform.Rotate(Vector3.left * rotationSpeed * deltaTime);
        }

        else if (!isTurningLeft && isTurningRight)
        {
            cube.transform.Rotate(Vector3.right * rotationSpeed * deltaTime);
        }
    }
}