So I'm trying to make a **2d side-scroller platformer**, but instead of using traditional "Left/Right" arrow keys or "A/D", I've created a **click to move controller ** that only moves the player horizontally. However I'm trying to **implement a jump mechanic** but I **cannot seem to get the jump to work** right with the click to move controls. Whenever I jump the character seems to have a varied jump velocity every time. Also when I walk off of platforms (to get to another platform below) the character seems to stop midair for a second then actually start to fall and I also think it is because of how my click to move controller is set up. Any suggestions/tips would be greatly appreciated! Here is my movement code:
public Rigidbody2D rb;
public float speed = 10f;
private Vector2 targetPosition;
private bool isMoving = false;
//grounded check for jumps
public float jumpVelocity = 10f;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
private void Update()
{
if (Input.GetMouseButton(0))
{
SetTargetPosition();
}
if (Input.GetKey(KeyCode.LeftShift))
{
isMoving = false;
}
if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
{
rb.velocity = Vector2.up * jumpVelocity * Time.deltaTime;
}
if (transform.position.y == targetPosition.y && transform.position.x == targetPosition.x)
{
isMoving = false;
}
}
private void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
if (isMoving)
{
rb.position = Vector3.MoveTowards(rb.position, targetPosition, speed * Time.deltaTime);
}
}
private void SetTargetPosition()
{
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
targetPosition.y = transform.position.y;
isMoving = true;
}
↧