Activating 3 rotations based on multiple presses on one key

Hi,

I am trying to create a sword swing with just built-in unity objects.

I have to make it so that when you press the action button once, it will rotate in one direction then press it again and rotates another direction and so on…

I’ve tried using Slerp and a timer which will cut off any button presses made but there is still a delay with each button press. I’m trying to do a 90 degree turn on the right direction and then a 90 degree turn on the forward direction and then a -90 degree turn on the right direction. However, it doesn’t seem to turn in a complete 90 degree direction and it goes all over the place.

Is there a way to get the input of each button press separately and get a clean and complete animation? Thanks!

What you’re trying to do revolves around what’s called “Coroutines”.

For a start you need a button state manager, a simple script that cycles a variable from 0 to 2 (A Vector3 is a zero based array with three elements from index 0 for x, 1 for y and 2 for z) on a same key press (probably best done with OnButtonDown).

After that, you need a coroutine (mock code) to be called inside Update

void Update () {
  //... other code

  if (Input.OnButtonUp(mysamekey)) {
    StartCoRoutine(rotateroutine(mycurrentaxis, 100));
  }
}

rotateroutine (axis, angles) {
for 1 to angles {
Vector3 newrotation;
newrotation[axis] = angles
transform.eulerAngles = newrotation;
}
}

Code certainly won’t compile, but should help you get on the right track.

I suggest using an int.

private int swingNum = 0;
private bool swinging = false;
public float swingTime = 2.0f;

void Update (){
if (Input.GetButtonDown("whatever")){
if (swinging == false){
 if (swingNum == 0){
 StartCoroutine("SwingOne");
 swingNum += 1;
 }
 if (swingNum == 1){
 StartCoroutine("SwingTwo");
 //from here onwards you would either add another digit to swingNum and put another
if statement asking if it is swingNum 2 or you would reset swing num to 0 again
Rinse and Repeat sort of deal`
    }
   }
  }

IEnumerator SwingOne () {
//do your rotation here
swinging = true;
yield return new WaitForSeconds(swingTime);
// return back to original position via your rotation or leave it where it has rotated to
swinging = false;
}
//Repeat the IEnumerator function with the different name and with different rotations etc

This is exactly what you want, you just need to fix the syntax and insert the rotations and swings.

Peace,

EDIT: You can also add a timer to how long it will wait until it reverts back to swing one if you don't click for ages while in between the second and third swing for instance.