@koyu2 Sorry for the inconvenience! I just noticed that even when your Character script is executed after the SkeletonRootMotion
component, adding a velocity vector to rigidbody2D.velocity
does not have the desired effect. RigidBody2D.MovePosition()
seems to not only set Rigidbody2D.velocity
accordingly, but also zero any future modifications of Rigidbody2D.velocity
after execution in the same frame.
There is a parameter skeletonRootMotionBase.AdditionalRigidbody2DMovement
available, which can be used to set additional movement. Unfortunately it seems to be quite complicated to set persistent velocities. Nevertheless, the following code would be an adjusted equivalent of your script code using AdditionalRigidbody2DMovement
:
public class Character : MonoBehaviour
{
public Rigidbody2D chrRigid;
protected SkeletonRootMotionBase rootMotion;
protected void Awake()
{
chrRigid = GetComponent<Rigidbody2D>();
rootMotion = GetComponent<SkeletonRootMotionBase>();
}
protected void FixedUpdate()
{
Vector2 additionalMovement = Vector2.zero;
float input_X = Input.GetAxis("Horizontal");
if (input_X != 0.0f) {
additionalMovement.x = 10 * input_X * Time.deltaTime;
}
if (Input.GetKey(KeyCode.Space)) {
additionalMovement.y = 30 * Time.deltaTime;
}
rootMotion.AdditionalRigidbody2DMovement = additionalMovement;
}
}
The following component would then check for grounding, set rootMotion.applyRigidbody2DGravity = !isGrounded2D;
and zero velocity upon grounding as well:
using UnityEngine;
public class ApplyGravityWhenGrounded : MonoBehaviour
{
public bool isGrounded2D = false;
protected SkeletonRootMotionBase rootMotion;
protected new Rigidbody2D rigidbody2D;
void Start () {
rootMotion = this.GetComponent<SkeletonRootMotionBase>();
rigidbody2D = this.GetComponent<Rigidbody2D>();
}
void OnCollisionStay2D (Collision2D collision) {
foreach (ContactPoint2D contact in collision.contacts) {
if (contact.normal.y > 0.5f) {
isGrounded2D = true;
rootMotion.applyRigidbody2DGravity = !isGrounded2D;
rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x, 0f);
return;
}
}
isGrounded2D = false;
rootMotion.applyRigidbody2DGravity = !isGrounded2D;
}
void OnCollisionExit2D (Collision2D collision) {
isGrounded2D = false;
rootMotion.applyRigidbody2DGravity = !isGrounded2D;
}
}
We will investigate whether we can provide a better solution out of the box which makes adding forces and velocities easier.