Minimum script needed to make character move left/right

Hello:

I’m new to unity and am trying to learn scripting. I thought it would be easier to just see what makes one action tick rather than looking at the whole controller code for the 2D tutorial. So, I just want to know what the bare minimum script necessary is - just walking, no running, etc. Thanks!

I think if you are a beginner you can start with one line of code.

Add this line of code to the update function of your script.

this.transform.Translate(Input.GetAxis("Horizontal"),0,0);

this moves the character on the X as with the Arrow keys or A and D.
Here you can add a speed Variable and the time.deltatime Variable.
Also you can start an animation when you do this.

3 Likes

I don’t need the “var canControl = true;”?

as in “this”.transform… you mean “Character” or whatever object is is receiving the input?

What is the difference between that line and this line: var h = Input.GetAxisRaw (“Horizontal”);

I understand one declares and defines “h” but it uses GetAxisRaw and without the ,0,0.

Do you mean this.

if(canControl == true)
{
float h = Input.GetAxis("Horizontal");
		
this.transform.Translate(h,0,0);
}

This is the same as what i did only you use a temp variable to store the input.

And the Raw and non Raw difference is that Raw on the keyboard only can be -1,0 or 1.

Also the canControl bool is usefull for controlling if the player may move or not.

1 Like

Ok, so Input.GetAxis might be used for an analog rather than the arrows or a d-pad. It can pick-up all the inbetween…

canControl isn’t necessary then unless at some point in the game the character enters into some vehicle or whatever?

What about where you are saying “this”? what is “this”? Is that whatever object you are assigning the attribute to?

Yes the Input.GetAxis is for more smooth gameplay. Also GetAxisRaw can be 0,5 but only with an anolog stick or steering wheel.

Also you can slow down the player with a Speed variable. So you can control his speed even more. It is also very important to use Time.deltaTime. This will move the player per Seconds and not per Frame.

And you are right on the “this” part. “this” stands for the GameObject where the script is attached to.
Also it is possible to make a public GameObject and control another gameobject trough another script. Like:

public GameObject Character;
public float Speed = 5f;
public bool canControl;

void Update()
{
	if(canControl == true)
	{
		float h = Input.GetAxis("Horizontal") * Speed;
				
		Character.transform.Translate(h*Time.deltaTime,0,0);
	}
}
3 Likes
using UnityEngine;

public class PlayerController2 : MonoBehaviour
{
    public float Speed = 5f;
   
    void Update()
    {
        float h = Input.GetAxisRaw("Horizontal");

        GetComponent<Rigidbody2D>().velocity = new Vector2(h, 0) * Speed;
    }
}
2 Likes

thank you this very helpful

Unrelated but this was posted the exact day I got my first laptop.