Reputation: 65
This is my player's jump code:
void Update()
{
float oldmoveHorizontal = moveHorizontal;
moveHorizontal = Joystick.Horizontal;
moveVertical = Joystick.Vertical;
if (isJumping == false && moveVertical >= .7f)
{
moveVertical = Speed * 70;
isJumping = true;
}
ball_move = new Vector2(moveHorizontal, moveVertical);
ball_rigid.AddForce(ball_move);
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Ground")
{
isJumping = false;
}
}
}
When ball touches under of the collider it can jump again. How can i block this situation ?
if you cant download: https://ibb.co/yVgXmrM
Upvotes: 0
Views: 491
Reputation: 65
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Ground")
{
foreach (ContactPoint2D item in col.contacts)
{
Debug.Log("Normal:" + item.normal);
if (item.normal.y > 0 && col.gameObject.tag == "Ground")
{
isJumping = false;
Debug.Log("Top of Collider");
}
}
}}
I found my solution with checking top side of collider. With this code way, if player touchs top side of collider, it's going to activate jump again.
Upvotes: 1
Reputation: 20259
One solution is to check the position of the collision points of the collision and see any of them is "low enough" from the center of your player to be a jumpable collision:
private Collider2D playerCollider;
private float playerJumpableOffset = 0.001;
void Start() { playerCollider = GetComponent<Collider2D>(); }
void OnCollisionEnter2D(Collision2D col)
{
float jumpableWorldHeight = transform.position.y - playerJumpableOffset;
for (int i = 0 ; i < col.contactCount && isJumping; i++)
{
Vector2 contactPoint = col.GetContact(i).point;
if (contactPoint.y <= jumpableWorldHeight)
{
isJumping = false;
}
}
}
Upvotes: 1