Answer the question
In order to leave comments, you need to log in
How to fix so that the character in Unity does not fly into "space" when jumping against the wall?
Good afternoon!
I'm self-taught because I don't understand a lot. I compiled a script for a Persian so that it would normally move, but all the time I received new bugs, therefore I collected the script from various sources. Everything seems to be working fine, but when jumping against the wall, the character flies into "space". Played with the ground search diameter values - does not help. I changed the search point from the Persian, it also does not work.
To understand the full script below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PControler2 : MonoBehaviour{
[SerializeField]
private int lives = 5;
[SerializeField]
private float speed = 3.0F;
[SerializeField]
private float jumpForce = 5.0F;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
new private Rigidbody2D rigidbody;
private Animator animator;
private SpriteRenderer sprite;
private int extraJumps;
public int extraJumpsValue;
private void Awake() {
rigidbody = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
sprite = GetComponentInChildren<SpriteRenderer>();
}
private void Start() {
extraJumps = extraJumpsValue;
rigidbody = GetComponent<Rigidbody2D>();
}
private void FixedUpdate() {
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
CheckGround();
}
private void Update() {
if (isGrounded == true)
{
extraJumps = extraJumpsValue;
}
if (Input.GetButton("Horizontal")) { Run();}
if (Input.GetButton("Jump")&& extraJumps > 0) { Jump();
extraJumps --;}
else if (Input.GetButton("Jump")&& extraJumps == 0 && isGrounded == true) {
}
}
private void Run() {
Vector3 direction = transform.right * Input.GetAxis("Horizontal");
transform.position = Vector3.MoveTowards(transform.position, transform.position + direction, speed * Time.deltaTime);
sprite.flipX = direction.x < 0.0F;
}
private void Jump() {
rigidbody.AddForce(transform.up * jumpForce, ForceMode2D.Impulse);
}
private void CheckGround() {
Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, 0.6F);
isGrounded = colliders.Length > 1;
}
}
Answer the question
In order to leave comments, you need to log in
The code:
It doesn't work because immediately after that, the CheckGround() function is called, in which the isGrounded variable is overwritten again:
Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, 0.6F);
isGrounded = colliders.Length > 1;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question