I am learning through making a 2D platformer and I want the character to launch into the air when they jump on an enemy’s head. I’ve had the most luck with forcemode2D but I’ve also tried MovePosition, which did not perform well at all. I can’t use Rigidbody2D.velocity because the character is not kinematic.
The problem with ForceMode2D.Impulse is that it is inconsistent. Sometimes I land on the enemy and shoot straight into the air really high, and other times I barely get any air and I don’t know why. Here is a link to see what I’m dealing with: Jump inconsistency - Album on Imgur
I’m looking at the API and not understanding what I should be doing different. If ForceMode2D is not the best way to do this, I would love to hear another way, but currently its the only way I can get close to what I want.
Here is the relevant code:
public float moveSpeed = 5f;
public float idleDirection;
public float jumpHeight = 10f;
public float enemyBoost = 13f;
public bool isGrounded = false;
public Rigidbody2D rb;
void Update()
{
Jump();
Vector3 movement = new Vector3(Input.GetAxis(“Horizontal”), 0, 0f);
transform.position += movement * Time.deltaTime * moveSpeed;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag(“WeakPoint”)) //detects if player jumped on enemy’s head
{
Destroy(collision.transform.parent.gameObject);
gameObject.GetComponent().AddForce(new Vector2(0f, enemyBoost), ForceMode2D.Impulse);
animator.SetTrigger(“Jump”);
animator.SetBool(“Jump Check”, false);
}
}
void Jump()
{
if (Input.GetButtonDown(“Jump”) && isGrounded == true)
{
gameObject.GetComponent().AddForce(new Vector2(0f, jumpHeight), ForceMode2D.Impulse);
animator.SetTrigger(“Jump”);
animator.SetBool(“Jump Check”, true);
}
}
}