Basic transform movement

    float speed;

    void Start()
    {
        speed = 20f;
    }

    void Update()
    {
        float posX = Input.GetAxis("Horizontal");
        float posY = Input.GetAxis("Vertical");
        Vector2 pos = transform.position;
        pos += new Vector2(posX * speed * Time.deltaTime, posY * speed * Time.deltaTime);
        transform.position = pos;
    }

Let’s change the code a bit so that we can confine Y axis movement. To achieve that we will use a Mathf.Clamp() method.

    float speed;

    void Start()
    {
        speed = 20f;
    }

    void Update()
    {
        float posX = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
        float posY = Input.GetAxis("Vertical") * Time.deltaTime * speed;
        Vector2 pos = transform.position;
        pos += new Vector2(posX, posY);
        pos.y = Mathf.Clamp(pos.y, -4f, 4f);
        transform.position = pos;
    }

Below we we get the same result as above but in a bit different way, we will use a Translate method.

    float speed;

    void Start()
    {
        speed = 20f;
    }

    void Update()
    {
        float posX = Input.GetAxis("Horizontal") * Time.deltaTime * speed;
        float posY = Input.GetAxis("Vertical") * Time.deltaTime * speed;
        transform.Translate(posX, posY, 0f);
        Vector2 pos = transform.position;
        pos.y = Mathf.Clamp(pos.y, -4f, 4f);
        transform.position = pos;
}

Dodaj komentarz

Twój adres email nie zostanie opublikowany.