Question by
studentnicki · Apr 05, 2018 at 08:34 AM ·
c#playerbugjumpjumping object
Player does not jump?
Does anybody know why my character wont jump?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private Rigidbody2D myRigidBody;
private Animator myAnimator;
[SerializeField] //enables to control the object from unity
private float movementSpeed;
private bool facingRight;
[SerializeField]
private Transform[] groundPoints;
[SerializeField]
private float groundRadius;
[SerializeField]
private LayerMask whatIsGround;
private bool isGrounded;
[SerializeField]
private bool airControl;
private bool jump;
[SerializeField]
private float jumpForce;
private float horizontal;
void Start()
{
facingRight = true;
myRigidBody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
}
private void Update()
{
HandleInput();
this.horizontal = Input.GetAxis("Horizontal");
}
void FixedUpdate()
{
//float horizontal = Input.GetAxis("Horizontal");
isGrounded = IsGrounded();
HandleMovement(this.horizontal);
Flip(horizontal);
HandleLayers();
ResetValues();
}
private void HandleInput()
{
if (Input.GetKeyDown(KeyCode.Space))
{
jump = true;
}
}
private void HandleMovement(float horizontal)
{
if (myRigidBody.velocity.y < 0)
{
myAnimator.SetBool("land", true);
}
if (isGrounded|| airControl)
{
myRigidBody.velocity = new Vector2(horizontal * movementSpeed, myRigidBody.velocity.y);
}
if (isGrounded && jump)
{
isGrounded = false;
myRigidBody.AddForce(new Vector2(0, jumpForce));
myAnimator.SetTrigger("jump");
}
myRigidBody.MovePosition(myRigidBody.position + new Vector2(horizontal * movementSpeed * Time.fixedDeltaTime, 0));
myAnimator.SetFloat("speed", Mathf.Abs(horizontal));
}
private void Flip(float horizontal)
{
if (horizontal > 0 && !facingRight || horizontal<0 && facingRight)
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
private void ResetValues()
{
jump = false;
}
private bool IsGrounded()
{
if (myRigidBody.velocity.y <= 0)
{
foreach(Transform point in groundPoints)
{
Collider2D[] colliders = Physics2D.OverlapCircleAll(point.position, groundRadius, whatIsGround);
for(int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
myAnimator.ResetTrigger("jump");
myAnimator.SetBool("land", false);
return true; //colliding
}
}
}
}
return false;
}
private void HandleLayers()
{
if (!isGrounded)
{
myAnimator.SetLayerWeight(1, 1);
}
else myAnimator.SetLayerWeight(1, 0);
}
}
Comment