My 2D character isnt moving with the arrow/'A','S','D','W' keys :( even the console shows no error pls help asap,My 2d Character isnt moving for some reason :( even the console show no errors pls help asap

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

public class NewBehaviourScript : MonoBehaviour
{
    
    public float speed = 5;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {

        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");

        Vector2 pos = transform.position;

        pos.x += h * Time.deltaTime;
        pos.y += v * Time.deltaTime;

        transform.position = pos;
    }

} // class

Greetings @shriyansofficial

I’ve copied your code and it works fine for me on a trivial project (just a circular sprite). There are three things you ought like to change.

  • You should really be multiplying by speed on lines 25 and 26, since you want to factor that in.

  • Also, since diagonal moves are 1 up and 1 across, the resulting distance is the hypotenuse of a right angle triangle, which is actually 1.414 in length. You should normalise the vector before using it so that you don’t move too quickly diagonally.

  • Use GetAxisRaw rather than GetAxis. You probably want to stop immediate on taking your finger off the button and you’ll need GetAxisRaw if you want to do that. Check the manual for differences between the two.

Are you sure that you attached the script to the sprite? Have a look at the transform to make sure that the X and Y values are actually changing. Anyway, here’s my version of your code:

using UnityEngine;

public class TempMove : MonoBehaviour
{
    public float speed = 5;

    void Update()
    {
        Vector3 move = Vector3.zero;

        move.x = Input.GetAxisRaw("Horizontal");
        move.y = Input.GetAxisRaw("Vertical");

        move = move.normalized * Time.deltaTime * speed;
        transform.position += move;
    }
}