- Home /
2D one distance at a time movement
Hello, I am trying to make a 2D game. But i can't find out how you can make a player move one distance at a time. By that I mean when you press the right arrow key your character moves form x to x + 1, then waites and if you are still holding it you move again 1 'block' to the right. So you are always above a block. Excpect when you are moving. I hope you understand.
-Nelis
Answer by xikky · Feb 19, 2013 at 05:24 PM
Not sure what you mean exactly, but I think this helps. This example uses WaitForSeconds function which pauses the Update for the delay given as the parameter. You can surely figure out the rest of the code.
private var moveCheck:boolean = true;
private var delay:int = 2;
function Update() {
if (moveCheck)
Move();
}
function Move() {
moveCheck = false;
yield WaitForSeconds(delay);
//Put code for movement here
moveCheck = true;
}
Thank you! :D And to clarify i mean a movement like in this flashgame : http://www.xgenstudios.com/game.php?keyword=motherload
Glad to help. It would be nice to turn the answer into the solution :) and such comments post them by the 'add new comment' for the sake of a well organised community ;)
How do you turn the answer into the solution? This is my first question ever :)
Answer by robertbu · Feb 19, 2013 at 06:43 PM
Here is a starting point. I wrote it as an answer to another question, but I think it gives you the motion you are looking for. Attach it to a cube and use the arrow keys to move.
public class MoveTheCube : MonoBehaviour {
Vector3 v3Delta = Vector3.zero;
Vector3 v3Accl = new Vector3(.005f, 0.0f, 0.0f);
float fFrictionFactor = 0.98f;
float fMaxSpeed = 0.5f;
void Update () {
if (Input.GetKey(KeyCode.RightArrow))
v3Delta += v3Accl;
if (Input.GetKey (KeyCode.LeftArrow))
v3Delta -= v3Accl;
v3Delta *= fFrictionFactor;
v3Delta.x = Mathf.Clamp (v3Delta.x, -fMaxSpeed, fMaxSpeed);
transform.Translate (v3Delta);
}
}