How can I get my object to move in only one direction at a time?
I am in the very basic stage of learning unity and am in a top down 2D setting. I am trying to get my object to move left a specific number of units and then down a specific number of units and then stop, but what it is doing is just moving diagonal and does not stop.
This is the script attatched to my object.
public class Movement : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
int leg=0;
switch (leg)
{
case 0:
MoveRight(20);
leg++;
break;
case 1:
MoveDown(20);
leg++;
break;
default:
break;
}
MoveDown(20);
MoveRight(20);
}
void MoveRight(int amount)
{
for (int i = 0; i < amount;i++)
{
transform.position = new Vector3(transform.position.x + .001f, transform.position.y);
}
}
void MoveLeft(int amount)
{
for (int i = 0; i < amount; i++)
{
transform.position = new Vector3(transform.position.x - .001f, transform.position.y);
}
}
void MoveUp(int amount)
{
for (int i = 0; i < amount; i++)
{
transform.position = new Vector3(transform.position.x, transform.position.y+.001f);
}
}
void MoveDown(int amount)
{
for (int i = 0; i < amount; i++)
{
transform.position = new Vector3(transform.position.x, transform.position.y - .001f);
}
}
}
This should be rejected for unformatted code, but I'll fix it for you. Remember to highlight pasted code and click the 101010 button.
Just so you know, you shouldn't make a habit of expecting volunteers to debug beginner's code. Perhaps the next guy will be feeling more charitable. ;)
Answer by ScaniX · Dec 28, 2016 at 01:19 PM
You have not added any condition that would make your movement stop. So for every frame (because you are using the Update()
callback) the object moves 0.4f (2 * 20 * 0.01f) to the right and 0.2f (1 * 20 * 0.01f) down.
Your switch statement does not work, because leg
is a local variable with the value of 0 as it gets initialized each frame like this. You would need to move it to a member variable to make that work.
Having a fixed size step per frame will not give you a nice movement anyway, but you should look up tutorials for that separately.
I'm giving you a very simple example on how to get a left/down movement with least possible changes to your existing code:
private int leg = 0;
private int amount = 20;
void Update() {
switch (leg)
{
case 0: // go left
MoveLeft(1); // only one step, loop in method can be removed
if (--amount == 0) { // switch to next step if amount is depleted
amount = 20; // back to 20, which is the amount we want to go down
leg++;
}
break;
case 1:
MoveDown(1);
if (--amount == 0)
leg++;
break;
default:
break;
}
}
Your answer
