Unity :CharacterMovement

Estimated reading: 1 minute 298 views Contributors

Displays movement and rotation logic using keyboard input

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

public class CharacterMovement : MonoBehaviour
{
    public float speed = 5.0f; // Movement speed

    void Start()
    {
        // Initialization logic (optional)
    }

    void Update()
    {
        // Get input from keyboard
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        // Calculate movement direction
        Vector3 movementDirection = new Vector3(horizontalInput, 0.0f, verticalInput);
        movementDirection.Normalize();

        // Move the character
        transform.Translate(movementDirection * speed * Time.deltaTime, Space.World);

        // Rotate character to face direction
        if (movementDirection != Vector3.zero)
        {
            Quaternion toRotation = Quaternion.LookRotation(movementDirection, Vector3.up);
            transform.rotation = Quaternion.RotateTowards(
                transform.rotation,
                toRotation,
                speed * Time.deltaTime
            );
        }
    }
}
Share this Doc

Unity :CharacterMovement

Or copy link

CONTENTS

Chat Icon Close Icon