Search Unity

Left and Right Movement In 2D

Discussion in 'Scripting' started by One_Knife_Games, Nov 23, 2014.

Thread Status:
Not open for further replies.
  1. One_Knife_Games

    One_Knife_Games

    Joined:
    Jul 19, 2013
    Posts:
    3
    I am trying to make a gameobject in Unity 4.6 move left and right. Basically, the gameobject, when pressed the key, d, moves forward on the x axis until w is released and again when the a key is pressed the gameobject moves backwards on the x axis.
     
  2. Tomnnn

    Tomnnn

    Joined:
    May 23, 2013
    Posts:
    4,148
    Without physics2D?
    Code (CSharp):
    1. if(Input.GetKey(KeyCode.A))
    2. {
    3.     transform.position += transform.right * -speed * Time.deltaTime;
    4. }
    With physics2D?
    add a rigidbody2D to the object, then try the following (I have all movements here because this is from a small 2D test I was doing). This will work with 2D physics so your object can't pass through other 2D colliders.

    Code (CSharp):
    1. Vector2 movement = Vector2.zero;
    2.  
    3.         if(Input.GetKey(KeyCode.A))
    4.         {
    5.             movement.x = (transform.right*Time.deltaTime*-moveSpeed).x;
    6.         }
    7.         if(Input.GetKey(KeyCode.D))
    8.         {
    9.             movement.x = (transform.right*Time.deltaTime*moveSpeed).x;
    10.         }
    11.         if(Input.GetKey(KeyCode.W))
    12.         {
    13.             movement.y = (transform.up*Time.deltaTime*moveSpeed).y;
    14.         }
    15.         if(Input.GetKey(KeyCode.S))
    16.         {
    17.             movement.y = (transform.up*Time.deltaTime*-moveSpeed).y;
    18.         }
    19.  
    20.         movement = movement + (Vector2)(transform.position);
    21.  
    22.         rigidbody2D.MovePosition(movement);
     
  3. One_Knife_Games

    One_Knife_Games

    Joined:
    Jul 19, 2013
    Posts:
    3
    Alright, I used the code with physics2D and these two errors appeared: (1,9) : error CS0116: A namespace can only contain types and namespace declarations and (3,2): error CS8025: Parsing error. I would normally try to fix them myself, however, I do not know much C#.
     
  4. Tomnnn

    Tomnnn

    Joined:
    May 23, 2013
    Posts:
    4,148
    That second one came straight out of a working example I'm going to teach a class on Tuesday, haha. I hope it's not a javascript error, most of that class if not all are using javascript...

    The first error sounds like you've got one extra bracket somewhere in your code. If you put this code in your Update function on an object that has a rigidbody2D, it should run fine. The second error has the same cause. Both CS0116 and CS8025 errors can be fixed if you check your brackets and make sure they all close. Every opening { needs a closing }. If you can't find the error, try posting the code here.
     
Thread Status:
Not open for further replies.