How to create a simple walking script (C#)?

Hi, I am a total newb in Unity and I am having problem with just the movement of my sprite…I have added a rigidbody2d to my sprite and collisionbox2d to the background. Set the collisionbox2d smaller in size for the ground only and done.

I am using MonoDevelop and I do not know much of C#. My main programming language is C++ so thankfully there’s some similarities.

using UnityEngine;
using System.Collections;

public class Walking : MonoBehaviour {
    public float WalkSpeed;
    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        if(Input.GetKey (KeyCode.LeftArrow))
        {
           //How do I start from here??
        }

    }
}

How do I get my player position axis and set it to (x -= WalkSpeed) ? Also my MonoDevelop keep showing this error

Sorry if I ask too much. The main problem is I do not know how my player is gonna use that movement script…The rigidbody gravity scale is set to 1 but when I click on the “Play” button, the sprite is not moving at all. Not even falling hitting the collisionbox2d… I am really new to Unity. Hopefully you guys can provide me with simple solution and let me figure out the rest. Thanks in advance.

sprite need colider2D too.

put sprite in the scene, add collider2D (box or circle) to them, add rigidbody2D. Make c# script with lines:

public float speed;
private float move;
void Update () {
move = Input.GetAxis("Horizontal");
rigidbody2D.velocity = new Vector2(move * speed, rigidbody2D.velocity.y);}

add it to sprite gameobject.

put ground sprite in the scene and add collider2D box (your player should go over collider and not in).

Horizontal have default key ad,left and right, i think. You can change it in project settings - input.

1 Like

thanks

I need a collider3D for my game. please help me

Add Component > Select any 3D Collider?

Hi I was wondering I have a 2d game and cant figure out how to do C# script to walk and jump can someone pls help me thanks!!!

Please create your own thread rather than necroing old posts. What you’re asking for is covered by many, many tutorials. A forum isn’t going to supply you with anything beyond what these tutorials will give you.

“walk and jump” also isn’t a single solution. Characters and games obviously have so many different dynamics but if you’re doing something basic then yes, plenty of 2D tutorials out there that a quick search will give you. Follow some of them, come back if you have a specific question.