- Home /
Question by
Wlahtuch · Feb 08, 2021 at 04:34 PM ·
script.scripting beginnermovement scriptstep
How to make a step-by-step movement in the Unity
Hi. I need to make the movement of the boat step by step. Each step is a movement of a certain distance. So that you can then count the steps. That is, you press the button once - one step. Without constant movement! Please tell me.
Then I want to count the number of steps and limit them.
Movements: 1.forward and to the right 2. forward and to the left 3. back and right 4. back and left
samplescene-1080p-08022021-09-14-08.jpg
(178.0 kB)
Comment
Best Answer
Answer by LoloBad · Feb 08, 2021 at 08:59 PM
Hi, Here is my code to do so. Your mobile GameObject must have a Character Controller as component (refered as cc in my code).
In the Update() method:
if (Input.GetKey(KeyCode.UpArrow))
{
isMoving = true;
StartCoroutine(MoveForward(10f));
}
Then the coroutine :
private IEnumerator MoveForward (float distance)
{
Vector3 startPosition = transform.position;
while (Vector3.Distance(startPosition, transform.position) < distance)
{
Vector3 shift = new Vector3(0f, verticalVelocity, speed);
shift = transform.rotation * shift;
cc.Move(shift * Time.deltaTime);
yield return null;
}
isMoving = false;
}