2D Player Controller Problem, cant jump while on the move
Okay, so I want to create a script that makes my character goes to left/right in constant speed. I achieved this, but sometimes the input isn't read. And I can't have my character to jump while on the move(it can if it's standing still). I'm using 2D sprite with box collider and rigidbody2d.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
public float speed = 200f;
public float jumpHeight = 200f;
Rigidbody2D rb;
Animator anim;
bool isMoving;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate(){
rb.velocity = rb.velocity.normalized * speed;
if(Input.GetKeyDown(KeyCode.A)) {
transform.localRotation = Quaternion.Euler(0,180,0);
rb.velocity = new Vector2( -speed * Time.deltaTime, 0 );
}
if(Input.GetKeyDown(KeyCode.D)){
transform.localRotation = Quaternion.Euler(0,0,0);
rb.velocity = new Vector2( speed * Time.deltaTime, 0 );
}
if(Input.GetKeyDown(KeyCode.W)){
rb.AddForce(new Vector2(0, jumpHeight));
}
}
}
Answer by Salmjak · Feb 16, 2016 at 12:14 PM
You always set the Velocity.y component to 0 when you go left/right. That's why it will always be 0 as long as you press A/D, addforce won't change that (maybe a bit, but it's still the source of your problem). Change your velocity vector to something like:
if(Input.GetKeyDown(KeyCode.A)) {
transform.localRotation = Quaternion.Euler(0,180,0);
rb.velocity = new Vector2( -speed * Time.deltaTime, rb.velocity.y ); //don't change the y-component of the original velocity.
}
Your answer
Follow this Question
Related Questions
Stop movement on collision 1 Answer
Isometric Movent Issue 0 Answers
Time.deltaTime problems 1 Answer
Using spawners script variable to set relevant speed of an Enemy... Im bewildered 1 Answer