Search Unity

Automatic Movement

Discussion in 'Scripting' started by KingAgni, Jul 24, 2014.

  1. KingAgni

    KingAgni

    Joined:
    May 2, 2014
    Posts:
    2
    Hello,

    I am making my very first game in Unity 2d. At the moment my game consists of 2 walls a floor, a ceiling, and a square which represents the character. After watching some tutorials I have created a C# character controller script which at the moment let's my player jump. Now that I can make the square jump, my next goal is to make the character move without having to press any buttons or making it think a button is being pressed.

    Question:

    How do I make my square move to the right automatically without any input from the user?

    Current Code:

    usingUnityEngine;
    usingSystem.Collections;

    publicclassSquareControllerScript : MonoBehaviour
    {
    boolgrounded = false;
    publicTransformgroundCheck;
    floatgroundRadius = 0.2f;
    publicLayerMaskwhatIsGround;
    publicfloatjumpForce = 700f;

    voidStart ()
    {

    }

    voidFixedUpdate()
    {
    grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatIsGround);

    }

    voidUpdate()
    {
    if (grounded && Input.GetKeyDown (KeyCode.Space))
    {
    rigidbody2D.AddForce(newVector2(0,jumpForce));
    }
    }
    }
     
  2. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008
    Rigidbody2d.velocity = new vector2(speed * time.deltaTime, 0)
     
    KingAgni likes this.
  3. KingAgni

    KingAgni

    Joined:
    May 2, 2014
    Posts:
    2
    @SubZeroGaming
    Thanks for the reply. I ended up coding it in this way before I saw your reply. I'll give your suggestion a try as well.
    rigidbody2D.velocity = newVector2(2, 0);
     
  4. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    without the deltatime your movement is directly tied to the frame rate, faster device => faster in game movement.

    using a variable rather than a set value (2 in this case) gives you a bit more freedom to tweak and change, and have the speed alterable via other scripts.
     
    KingAgni likes this.