Home > OS >  2D character not moving. Console shows no errors
2D character not moving. Console shows no errors

Time:10-06

I couldn't find any mistakes in this code. if there aren't any mistakes in the code, please let me know what's wrong.

```
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

```

CodePudding user response:

Try putting Horizontal and Vertical values in a Vector2 Then do transform.Translate(Movement * speed * Time.deltaTime); Instead of adding the position. Also you forgot to multiply the position by the speed. The Update should look something like this.

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

        Vector2 Movement = Vector2.zero;
        Movement.y = v;
        Movement.x = h;

        transform.Translate(Movement * speed * Time.deltaTime);

CodePudding user response:

I think your issue is that you forgot to include the speed multiplier in your code, so the correct code should be this

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 * speed * Time.deltaTime; //Multiply h by speed
        pos.y  = v * speed * Time.deltaTime; //Multiply v by speed

        transform.position = pos;
    }


} // class
  • Related