Cant move and jump at the same time. Only every couple frames you can jump.
For some reason my player cannot jump up and move left and right at the same time. Its wierd. Here is the controller script. This is a 2D Platformer.
public class PlayerController : MonoBehaviour { // Movement Settings [Header("Movement Settings:")] [Space] [Range(1, 10)] public float movementSpeed; [Range(1, 10)] public float jumpHeight;
private bool canJump;
// Components
private Rigidbody2D rigid;
void Start()
{
// Set Components to their Corresponding Variables
rigid = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
// Jumping
if(canJump && Input.GetKeyDown(KeyCode.W))
{
rigid.AddForce(Vector2.up * jumpHeight, ForceMode2D.Impulse);
}
}
void Update()
{
// Movement Left or Right
Vector3 moveDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0, 0);
transform.Translate(moveDirection * movementSpeed * Time.deltaTime);
// Check if Player is Grounded
Vector2 groundCheckStart = new Vector2(transform.position.x, transform.position.y - 0.55f);
Vector2 groundCheckEnd = new Vector2(transform.position.x, transform.position.y - 0.6f);
Debug.DrawLine(groundCheckStart, groundCheckEnd, Color.red);
RaycastHit2D groundCheck = Physics2D.Linecast(groundCheckStart, groundCheckEnd);
if (groundCheck.collider != null)
{
canJump = true;
}
else
{
canJump = false;
}
}
}
Answer by Centarius · Jan 16, 2017 at 08:24 AM
Hi @jakubshark, I think the problem is that you're getting Input from two different Update functions. Try moving everything to the FixedUpdate function.
Good Luck and Happy Coding!
Answer by ScaniX · Jan 16, 2017 at 01:36 PM
Input should be retrieved in the Update() as it is cleared per frame, which is the frequency of the Update() method.
You should not get Input() in the FixedUpdate() as that one is usually only called every few frames. As you are triggering physics, you can store the fact that the player pressed jump and add the force in the next FixedUpdate.
I doubt that this single AddForce for jumping would behave badly when done in the Update(), so you could try that as well.
Your answer
Follow this Question
Related Questions
Player passenger moving when being pushed by two platforms 0 Answers
Character flickering on moving platform 3 Answers
Having a couple of problems regarding 2D Movement. 1 Answer
Platformer 2D 1 Answer