Question by
kzhang3742 · Aug 14, 2020 at 04:01 PM ·
movement2d-platformercrouching
player can only jump or move during crouch, not both
first time asking a question so im not sure if im doing it right
im making a 2d platformer where i want my character to be able to crouch jump while moving like in mario. His movement while not crouching is perfect but when i make him crouch, i can only choose between moving him left and right or jumping instead of both at the same time.
here is my code(isCeil & isGrounded are edited by a different script):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
//variables
public Rigidbody2D rb;
public float moveSpeed = 15f;
public float crouchSpeed = 10f;
public float jumpHeight = 12f;
public bool isGrounded = false;
public bool isCeil = false;
void Start()
{
}
void Update()
{
IsMoving();
Movement();
}
void Movement()
{
//Crouch
if (isCeil == true)
{
Jump();
if (Input.GetKey(KeyCode.A))
{
rb.velocity = new Vector2(-crouchSpeed, rb.velocity.y);
}
if (Input.GetKey(KeyCode.D))
{
rb.velocity = new Vector2(crouchSpeed, rb.velocity.y);
}
}
else if (Input.GetKey(KeyCode.S))
{
Jump();
if (Input.GetKey(KeyCode.A))
{
rb.velocity = new Vector2(-crouchSpeed, rb.velocity.y);
}
if (Input.GetKey(KeyCode.D))
{
rb.velocity = new Vector2(crouchSpeed, rb.velocity.y);
}
}
//LeftRight Movement
else
{
Jump();
if (Input.GetKey(KeyCode.A))
{
rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
}
if (Input.GetKey(KeyCode.D))
{
rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
}
}
}
//Jump
void Jump()
{
if (Input.GetKey(KeyCode.W) && isGrounded == true)
{
rb.velocity = new Vector2(rb.velocity.x, jumpHeight);
}
}
//Stops Character From Sliding
void IsMoving()
{
if (!Input.GetKey(KeyCode.W) && !Input.GetKey(KeyCode.D) && !Input.GetKey(KeyCode.A))
{
rb.velocity = new Vector2(0, rb.velocity.y);
}
}
}
Comment