- Home /
Question by
arnoldkmwaura · May 24, 2018 at 08:50 AM ·
2d game2d-physics2d-gameplay2d platformer
When my 2d character is moving to the right it can jump to or fall from a platform but when it moves to the left it can't jump or fall from a platform. Here's the code I'm using.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class player : MonoBehaviour { private Rigidbody2D myRigidbody;
private Animator myAnimator;
Vector2 moveForward;
bool canGoForward = true;
bool canGoBack;
private bool facingRight;
[SerializeField]
private Transform[] groundPoints;
[SerializeField]
private float groundRadius;
[SerializeField]
private LayerMask whatIsGround;
private bool isGrounded;
private bool jump;
[SerializeField]
private float jumpForce;
// Use this for initialization
void Start()
{
facingRight = true;
myRigidbody = GetComponent<Rigidbody2D>();
myAnimator = GetComponent<Animator>();
}
// Update is called once per frame
void FixedUpdate()
{
if (canGoForward)
{
moveForward = myRigidbody.transform.position;
moveForward.x += 0.05f;
myRigidbody.transform.position = moveForward;
}
if (canGoBack)
{
moveForward.x -= 0.05f;
myRigidbody.transform.position = moveForward;
}
if (Input.GetKey(KeyCode.A))
{
canGoForward = false;
canGoBack = true;
}
if (Input.GetKey(KeyCode.D))
{
canGoForward = true;
canGoBack = false;
}
float horizontal = Input.GetAxis("Horizontal");
isGrounded = IsGrounded();
HandleMovement(horizontal);
Flip(horizontal);
if (isGrounded && jump)
{
isGrounded = false;
myRigidbody.AddForce(new Vector2(0, jumpForce));
}
if (Input.GetKey(KeyCode.W))
{
jump = true;
}
if (myRigidbody.velocity.y > 0)
{
jump = false;
}
}
// ignore this
private void HandleMovement (float 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 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)
{
return true;
}
}
}
}
return false;
}
}
Comment
Your answer
Follow this Question
Related Questions
Why didnt my Collider works? 0 Answers
Adding knockback to a 2D game (in C#) 2 Answers
How can I stop hurt animation and bounce the player when hit by an enemy? 0 Answers
How to detect if a specific side of a collider is touching another collider 3 Answers
Having some stuck issues on the 2D infinite runner 0 Answers