- Home /
Can't move left or right with my movement script
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float JumpForce;
bool isGrounded = false;
public float RightForce;
public float LeftForce;
Rigidbody2D RB;
void Awake()
{
RB = GetComponent<Rigidbody2D>();
}
void Update ()
{
if (Input.GetKey(KeyCode.UpArrow))
{
if(isGrounded == true)
{
RB.AddForce(Vector2.up * JumpForce);
isGrounded = false;
}
{
if (Input.GetKey(KeyCode.RightArrow))
{
if(isGrounded == true)
{
RB.AddForce(Vector2.right * RightForce);
isGrounded = false;
}
if (Input.GetKey(KeyCode.LeftArrow))
{
if(isGrounded == true)
{
RB.AddForce(Vector2.left * LeftForce);
isGrounded = false;
}
}
}
}
}
}
void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("ground"))
{
if(isGrounded == false)
{
isGrounded = true;
}
}
}
}
Comment
@Brxdman Have you checked whether isGrounded
ever actually gets set to true? Is it only left and right that are not working?
I'm on mobile at the moment, so it's very hard to read. It kinda looks like several of your if(KeyCode)
checks are nested within each other. That's probably your issue.
Why nesting your input conditions??
if(upArrow)
{
if(rightArrow)
{
if(leftArrow)
{
}
}
}
Don't you want
if(upArrow)
{
}
if(rightArrow)
{
}
if(leftArrow)
{
}
Answer by rh_galaxy · Apr 03 at 09:35 PM
This is probably what you want, see other comments
if(isGrounded == true)
{
if (Input.GetKey(KeyCode.UpArrow))
{
RB.AddForce(Vector2.up * JumpForce);
isGrounded = false;
}
if (Input.GetKey(KeyCode.RightArrow))
{
RB.AddForce(Vector2.right * RightForce);
isGrounded = false;
}
if (Input.GetKey(KeyCode.LeftArrow))
{
RB.AddForce(Vector2.left * LeftForce);
isGrounded = false;
}
}
Your answer
Follow this Question
Related Questions
2D Animation does not start 1 Answer
Trying to reset lvl on collsion 1 Answer