NinjaNube008
NinjaNube008

Reputation: 43

How would I temporarily rotate an object on the z-axis in Unity3D?

I'm trying to make a punch animation in Unity3D for a character, I need to rotate the arm on the z-axis, but have it animate, I've looked around everywhere for a solution. Nothing seems to work. Here's what I have so far:

PlayerMotor:

public void Punch() {
    arm.transform.Rotate(0, Time.deltaTime, 0);
    arm.transform.position= new Vector3(arm.position.x, arm.position.y, arm.position.z + .01f);
}

public void PunchReturn() {
    arm.transform.Rotate(0, -Time.deltaTime, 0);
    arm.transform.position = new Vector3(arm.position.x, arm.position.y, arm.position.z - .01f);
}

PlayerController:

if (Input.GetMouseButtonDown(0)) {
    // Does punching animation
    Debug.Log("punching");
    for (int i = 0; i < 50; i++) motor.Punch();
    for (int i = 0; i < 50; i++) motor.PunchReturn();
}

Upvotes: 0

Views: 65

Answers (1)

konsfik
konsfik

Reputation: 97

I agree with "trollingchar", coroutines or animator is the way to go. In case you want to try with coroutines:

make this method:

// this runs "in parallel" to the rest of your code.
// the yield statements will not freeze your app.
IEnumerator AnimationCoroutine(){
    for (int i = 0; i < 50; i++) {
        motor.Punch(); // rotate a little bit
        yield return null; // waits for one frame
    }
    for (int i = 0; i < 50; i++) {
        motor.PunchReturn(); // rotate a little bit
        yield return null; // waits for one frame
    }
}

and call it from the controller

if (Input.GetMouseButtonDown(0)) {
    // Does punching animation
    Debug.Log("punching");
    StartCoroutine(AnimationCoroutine());
}

Upvotes: 1

Related Questions