[FOR BEGGINERS] Simple movement code

If you just want a character that moves, nothing too special, try using this:

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

public class Movement : MonoBehaviour
{
    public float speedX;
    public float speedZ;
    public float speedXMIN;
    public float speedZMIN;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey("w"))
    {
        transform.Translate(speedX, 0, 0);
    }
        if (Input.GetKey("s"))
        {
            transform.Translate(speedXMIN, 0, 0);
        }
        if (Input.GetKey("d"))
        {
            transform.Translate(0, 0, speedZMIN);
        }
        if (Input.GetKey("a"))
        {
            transform.Translate(0, 0, speedZ);
        }

    }
}

NOTE: for MIN vars use negative values from the non-MIN vars. ex: if speedX is 0.5 then speedXMIN is -0.5. Attach the script to the object you want to move. Change the speed from the inspector (select object > scroll to code property > change vars to a number).

I honestly don’t see why anyone would do something like this instead of just using the default character controller component and using it’s move function.

Or even if you want to use the script you’re posting, just use a vector3 of your inputs.

Vector3 mov = new Vector3(Input.GetAxis("Horizontal"),0,Input.GetAxis("Vertical");
transform.Translate(mov * Time.deltaTime);

Honestly what you posted would just be promoting bad habits.

2 Likes

Not to mention, it completely ignores collision. Action gameplay is one of the easiest things to understand and implement in Unity, which is what tutorials are usually made about, and what beginners usually start with. Unity naturally tends towards movement and physics based games by virtue of the character controller being dogshit lousy, leaving the only alternative being the rigidbody. However, even the character controller is at least capable of accounting for static object collision, your “solution” isn’t.

2 Likes