Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Can You Explain 2d Movement in C#?

Discussion in '2D' started by ColouredPixelsUnity, Sep 16, 2015.

  1. ColouredPixelsUnity

    ColouredPixelsUnity

    Joined:
    Aug 10, 2014
    Posts:
    78
    Hi! I was wondering if someone could tell me the basic 2d platformer movement for C#. I know you'll need a 2d rigid body for gravity but I don't know how to get the player to move side to side and jump. Thanks.
     
  2. originalterrox

    originalterrox

    Joined:
    Feb 6, 2015
    Posts:
    40
    Affect the transform.position.x and transform.position.y, do not touch transform.position.z
    Usually use Addforce() in FixedUpdate() to move the rigidbody2D
    Also you will probbaly need to use Orthographic camera.
     
  3. ColouredPixelsUnity

    ColouredPixelsUnity

    Joined:
    Aug 10, 2014
    Posts:
    78
    Really? That simple? Ok, but how do u make it jump?
     
  4. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    rigidbody2D.AddForce(new Vector2(0, jumpPower)); :D
     
  5. originalterrox

    originalterrox

    Joined:
    Feb 6, 2015
    Posts:
    40
    be aware that the shortcut reference to rigidbody2D is a unity 4 thing, http://docs.unity3d.com/ScriptReference/GameObject-rigidbody2D.html
    left/right movement is basically rigidbody2D.AddForce(new Vector2(movespeed, 0));
    You can see that the addforce is adding x,y and you just use what you need.
    Sometimes you need to set velocity to 0,0 before you add force in situations where you don't want the jump or movement to add to existing momentum.