Search Unity

Movement Script for 2d and 3d games

Discussion in '2D' started by giladbarilan, Jan 20, 2020.

  1. giladbarilan

    giladbarilan

    Joined:
    Nov 11, 2019
    Posts:
    1
    Movement Script for 2D games
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Move : MonoBehaviour
    {
    public Rigidbody2D rb; //the rigidbody refrence will be for the player you want to move
    public Vector2 vectorX; //keep the y value to be 0
    public Vector2 vectorY; // keep the x value to be 0

    // Update is called once per frame
    void Update()
    {
    if (vectorX.x > 0) //not that important, important only if you changing the value in game of the vector x to be negetive by mistake
    {
    if (Input.GetKey("d"))
    {
    rb.AddForce(vectorX);
    }
    if (Input.GetKey("a"))
    {
    rb.AddForce(-vectorX);
    }
    }
    else if(vectorX.x<0)
    {
    if (Input.GetKey("d"))
    {
    rb.AddForce(-vectorX);
    }
    if (Input.GetKey("a"))
    {
    rb.AddForce(vectorX);
    }
    }
    if(vectorY.y>0)
    {
    if (Input.GetKey("s"))
    {
    rb.AddForce(-vectorY);
    }
    if (Input.GetKey("w"))
    {
    rb.AddForce(vectorY);
    }
    }
    if (vectorY.y < 0)
    {
    if (Input.GetKey("w"))
    {
    rb.AddForce(-vectorY);
    }
    if (Input.GetKey("s"))
    {
    rb.AddForce(vectorY);
    }
    }
    }
    }
     
  2. Cornysam

    Cornysam

    Joined:
    Feb 8, 2018
    Posts:
    1,466
    Couple things here:
    1. Please post your code using code tags from the text ribbon. It is much easier to read than what you posted.
    2. Is there a question? You just posted some code and didnt elaborate on anything.
     
    eses likes this.
  3. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    Neither does the question topic include a question...
     
    Cornysam likes this.