Player Movement Problem (Vector3)

Hey I’m having trouble making an object move. Here’s my code so far:

    public int speed = 5;
    Vector3 playerPosition = new Vector3 (transform.position.x, transform.position.y);
   
    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.A))
        {
            playerPosition.x -= speed;
        }
    }

You’re changing a variable named “playerPosition”. It’s not bound to the player’s position in any way.

When you do this:

Vector3 playerPosition = new Vector3 (transform.position.x, transform.position.y);

You’re copying the player’s current position. Changing that playerPosition variable doesn’t apply changes back to the player.

Just move the player directly, you don’t need the variable here:

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.A))
        {
            transform.position -= new Vector3(speed, 0f, 0f);
        }
    }

You should look through some of the official tutorials! They’re a good into to basic scripting. Check out the learn link on top of this page.

Also your code here is framerate dependent.
This means that, as your framerate vary, your transform speed vary aswell.
To make this framerate independant, you have to multiply the “delta movement” byt the “deltaTime”
delta movement being the movement between 2 frame, and deltaTime being the time elapsed between two frame.

    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.A))
        {
            transform.position -= new Vector3(speed, 0f, 0f) * Time.deltaTime;
        }
    }

As Baste said, this is well explained in the basic unity tutorial. Go look it up !

1 Like