Search Unity

What am I doing wrong in my movement script?

Discussion in '2D' started by Hampy, Apr 20, 2017.

  1. Hampy

    Hampy

    Joined:
    Apr 20, 2017
    Posts:
    1
    So I'm kinda new to this whole unity thing. I've been programming in C# for a while now and usually in order for something to move I'd just do a little "_playerPosition.x += 5;" but I tried that in Unity and it doesn't seem to work.
    This is my current movement code:

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

    public class PlayerMovement : MonoBehaviour {
    Vector2 _playerPosition;
    // Use this for initialization
    void Start () {
    _playerPosition = Vector2.zero;
    }

    // Update is called once per frame
    void Update () {
    if (Input.GetKeyDown(KeyCode.W)) {
    _playerPosition.y += 5f;
    }

    if (Input.GetKeyDown(KeyCode.S)) {
    _playerPosition.y -= 5f;
    }

    if (Input.GetKeyDown(KeyCode.D)) {
    _playerPosition.x += 5f;
    }
    if (Input.GetKeyDown(KeyCode.A)) {
    _playerPosition.x -= 5f;
    }
    }
    }
     
  2. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,508
    Well, thats probably because _playerPosition isn't being used by anything. Naming something "player position" doesn't make it actually do anything to the player position.

    Assuming that this script is on the player, after you capture the inputs and put them into _playerPosition, you can do:
    Code (csharp):
    1. transform.position = _playerPosition;
    Or something to that affect. In other words, actually use the vector to modify the Transform. Read about Transform's in the Unity documentation if you're confused. Or, just back up and do some of the many official tutorials.

    Also, use [code ] [/code] tags to wrap your code so its actually legible.