Say my player jumps off from a certain point on a 2D surface. Say my surface is uneven, and has varying y positions along the level, how would I then be able to time my jump animation accordingly? (The issue being is that the animation might get cut off half way through, or vice versa - the animation would be already finished while the player is still jumping/landing)
-
\$\begingroup\$ Can you give us a bit more detail about exactly what kind of animation/transition you're trying to implement, and how it relates to the height of the surface? There are a number of possibilities, and we want to make sure you get advice that's relevant to the approach you're using. \$\endgroup\$– DMGregory ♦Mar 18, 2018 at 0:26
1 Answer
Usually, when working on jumping mechanics, instead of relying on the duration of the animation, the motion is split in 3 (sometimes even more, but most of the times 3 is enough) animations:
- Jump from the ground animation
- in air /falling animation
- landing animation
In Unity, you could merge these three animations inside a blendtree while changing its state (jumping/in air/landing) based on a boolean parameter which is usually called isGrounded
.
IsGrounded
, as the name implies, checks if the player is grounded. To set this variable properly, there are two main ways:
you could either shoot a Raycast from the character origin to the ground(it has to be parallel to the global y axis);
or a sphere Cast(the same a raycast, but it's using a sphere mesh, to get a bit more precision).
You can see the two different approaches described in more detail here
Via the player script, you can just set isGrounded
's value inside with:
Animator anim;
bool value;
void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
// set 'value' to true if the player is grounded, set it to false if it's not
//then set the isGrounded bool inside the animator
anim.SetBool("isGrounded",value);
}