Tuesday, June 9, 2015

unity - How does one make both movement and animation to sync up and happen simultaneously?


I am very new to Unity and game making and would appreciate if you would cope with me.


I have made a very basic prototype of character animation and movement, however trigger that is supposed to fire animation happens after character already moved. I just can't seem to find a way to fix it as SetTrigger is void and not a Task.


See this video for what I mean


animated gif



The script I am using to fire off animation is the following:


public class Hero : MonoBehaviour {

public Animator animator;
public void Down()
{
var move = GameObject.Find("Hero").transform.position;
animator.SetTrigger("moveDown");
transform.position = Vector3.Lerp(move, move + new Vector3(0, -1f, 0), 1f);
}

}

How does one make both movement and animation to sync up and happen simultaneously?



Answer



You are trying to move the character from one point to another within the single method Down. This is not going to work, because that whole method is executed in a single frame. Vector3.Lerp just by itself doesn't cause a position to change slowly. All it does is calculate a position between two positions and return that as a new vector. This is a tool which can be useful for doing a gradual transition, but just by itself it doesn't do that.


What you should do instead is have Down set the information that the character is walking somewhere and then do the actual position updating in Update.


It should look something like this (untested!):


public class Hero : MonoBehaviour {

public Animator animator;

private Vector3 moveDestination;
private float moveTime = 0.0f;

private void Start() {
moveDestination = transform.position;
}

public void Down()
{
// when the character isn't already moving, move it down

if (moveTime <= 0.0f) {
moveDestination = transform.position + new Vector3(0, -1f, 0)
moveTime = 1.0f;
animator.SetTrigger("moveDown");
}
}

public void Update() {
if (moveTime > 0.0f) {
moveTime -= Time.deltaTime;

transform.position = Vector3.Lerp(moveDestination, transform.position, moveTime);

if (moveTime <= 0.0f) {
animator.SetTrigger("idle");
}
}
}
}

Also you need to remove transition duration

Click on transition arrow in Animator window, then in Inspector window expand Settings under Has Exit Time and set both Transition Duration and Transition Offset to 0.


enter image description here


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...