- Home /
Move player on predetermined looping path
Hi all,
I am a begginer developer and I am having difficulties coding the following problem( 2D):
While the button down is pressed, the player should move:
from the starting position down -2 spaces
then up 2 spaces
loop this down 2, up 2 spaces until the button is released
Continue on the current y coordinate (x never changes)
when pressed again, the movement should repeat from the new y coord.
The opposite should work if button Up is pressed.
If tried implementing it with Mathf.Sin(Time.time), but if I repeat the button press, instead of restarting and going down, it remembers the last played position and continues going i.e. up, instead of starting down.
Any help is very much appreciated!
Answer by Cassos · May 02, 2020 at 06:25 PM
Damn, I'll write you some code :P
public void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
StartCoroutine(MoveOnPath(currentIndex));
}
[Header("Movement")]
public float moveSpeed = 10;
public float maxDistanceToTarget = 0.2f;
public bool autoContinue;
public bool isRelativeMovement; // Relative to players position
[Space]
public Vector2[] path;
int currentIndex;
public IEnumerator MoveOnPath(int pathIndex)
{
currentIndex = pathIndex;
if (path.Length <= pathIndex) // Stops the Courotine if the pathIndex is higher than the counter of the path positions
yield break;
Vector2 tarPos = path[currentIndex];
if (isRelativeMovement)
tarPos += (Vector2)transform.position;
while (Vector2.Distance(transform.position, tarPos) > maxDistanceToTarget) // Moves to target as long as the position is out of reach (maxDistanceToTarget)
{
transform.position = Vector3.MoveTowards(transform.position, tarPos, Time.deltaTime * moveSpeed);
}
int nextIndex = currentIndex++;
if(nextIndex >= path.Length)
nextIndex = 0; // If the last point is reached it restarts from the beginning
if (autoContinue)
StartCoroutine(MoveOnPath(nextIndex)); // Restarts the whole process with the next waypoint!
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612233120im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Fuel bar doesn't work! 1 Answer
Player Going through colliders 1 Answer
Orbit player around center point 1 Answer