0

I'm following a tutorial on making a game but when I wrote what they wrote it wouldn't move.

The script is attached to sprite but when I hit W, A, S or D it doesn't move.

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

public class Movment : MonoBehaviour
{
    // Start is called before the first frame update

    public float speed = 5f;
    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;
           pos.y += v * speed * Time.deltaTime;
    }
}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75

1 Answers1

3

Since Vector2 is a value type (a struct), Vector2 pos = transform.position will make a copy of the transform position and the original position remains unaffected by any changes you make to pos. To update the position, use transform.position = pos once pos is set to the new position:

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

    Vector2 pos = transform.position;

    pos.x += h * speed * Time.deltaTime;
    pos.y += v * speed * Time.deltaTime;
    transform.position = pos;
}

See: What's the difference between struct and class in .NET?

JosephDaSilva
  • 1,107
  • 4
  • 5