Question by
Boue · Mar 29, 2016 at 02:44 PM ·
charactercontrollerjumpingcharacter controllercharacter movement
How to move a character in one direction only when jumping?
I'm trying to figure out how to make it so that my 2d character can only move the direction the player jumped instead of being able to go all over the place. I am extremely new to unity and C#, so I'm not even sure where to begin. I have walking and jumping down so far, and it looks like this:
public class Zanecontroller : MonoBehaviour {
public float footspeed;
public float jumpheight;
public Transform groundcheck;
public float groundcheckradius;
public LayerMask whatisground;
private bool grounded;
void Start () {
}
void FixedUpdate () {
grounded = Physics2D.OverlapCircle (groundcheck.position, groundcheckradius, whatisground);
}
void Update () {
if (Input.GetKeyDown (KeyCode.Space) && grounded) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (GetComponent<Rigidbody2D> ().velocity.x, jumpheight);
}
if (Input.GetKeyDown (KeyCode.A)) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (-footspeed, GetComponent<Rigidbody2D> ().velocity.y);
}
if (Input.GetKeyDown (KeyCode.D)) {
GetComponent<Rigidbody2D> ().velocity = new Vector2 (footspeed, GetComponent<Rigidbody2D> ().velocity.y);
}
}
}
Thank you for you help!
Comment
Answer by Ali-hatem · Mar 30, 2016 at 09:01 AM
private float h;
private bool FacingLeft;
Rigidbody2D rgb; // make instance for Rigidbody2D .
void Start(){
rgb = GetComponent<Rigidbody2D> (); // get Rigidbody2D component once @ Start .
}
void Update () {
if (Input.GetKeyDown (KeyCode.Space) && grounded) {
rgb.velocity = new Vector2 (rgb.velocity.x, jumpheight);
}
h = Input.GetAxis ("Horizontal"); // move only when input
if (h < 0 && grounded) {
FacingLeft= true;
if(FacingLeft)
rgb.velocity = new Vector2 (h * footspeed, rgb.velocity.y);
}
if (h > 0 && grounded) {
FacingLeft= false;
if(!FacingLeft)
rgb.velocity = new Vector2 (h * footspeed, rgb.velocity.y);
}
}
Your answer
Follow this Question
Related Questions
how to jump in a 2D game 2 Answers
Character moves opposite ways.,My character moves perfectly to every direction except -z. 0 Answers
How can I modify this to allow jumping with space? 0 Answers
Character Controller move overrides transform.position 0 Answers
Character jumps immediately after it's grounded when jump is pressed mid-air 2 Answers